Sai A Sai A
Updated date Nov 30, 2023
In this blog, we will explore how to convert Int to Fixed-Point in C. Learn how to cast integers to fixed-point using two practical methods, complete with easy-to-understand explanations and runnable C programs.

Introduction:

Fixed-point arithmetic is a technique used in programming to handle fractional numbers without relying on floating-point arithmetic, which can be computationally expensive on some platforms. In this blog, we will explore how to cast an integer to fixed-point in C,

Method 1: Using Integer Multiplication

One common method to convert an integer to fixed-point is by using integer multiplication. Consider the following C program:

#include <stdio.h>

#define INT_BITS 16  // Number of integer bits
#define FRAC_BITS 16 // Number of fractional bits

// Function to convert integer to fixed-point
int intToFixedPoint(int num) {
    return num << FRAC_BITS;
}

int main() {
    int integerNumber = 42;
    int fixedPointNumber = intToFixedPoint(integerNumber);

    printf("Integer: %d\nFixed-Point: %d\n", integerNumber, fixedPointNumber);

    return 0;
}

Output:

Integer: 42
Fixed-Point: 2752512

In this method, we shift the bits of the integer to the left by the number of fractional bits (FRAC_BITS). The left shift operation effectively multiplies the integer by 2^FRAC_BITS, converting it to a fixed-point representation. In the example, 42 is shifted left by 16 bits, resulting in 2752512.

Method 2: Using Explicit Conversion

Another approach involves explicitly converting the integer to a fixed-point representation by dividing it by 2^FRAC_BITS. Here's a C program illustrating this method:

#include <stdio.h>

#define FRAC_BITS 16 // Number of fractional bits

// Function to convert integer to fixed-point
int intToFixedPoint(int num) {
    return num * (1 << FRAC_BITS);
}

int main() {
    int integerNumber = 42;
    int fixedPointNumber = intToFixedPoint(integerNumber);

    printf("Integer: %d\nFixed-Point: %d\n", integerNumber, fixedPointNumber);

    return 0;
}

Output:

Integer: 42
Fixed-Point: 2752512

In this method, we multiply the integer by 2^FRAC_BITS, achieving the fixed-point representation. The result is the same as in Method 1, demonstrating an alternative way to perform the conversion.

Conclusion:

This blog has explored the various methods for converting an integer to fixed-point in C. The choice between them depends on your preference and the specific requirements of your program. Fixed-point arithmetic can be a powerful tool in situations where floating-point arithmetic might be impractical or too resource-intensive.

Comments (0)

There are no comments. Be the first to comment!!!