Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Observing bits from a variable in C/C++

Tags:

c++

c

binary-data

I would like to read in a number, say a float, and allow the user to see what bit pattern is responsible for their input. How do I allow a variable to be printed or stored as an int or array as simple binary values instead of 0-9 or a-z, etc?

This doesn't do what I want it to. It instead gives an int with digits 0-9, which is obviously not a binary number.

int main(){

cout << "Please enter a float number." << endl;
float number;
    cin >> number;

    int bits = *((int*) &number);

    cout << number << endl;

    cout << bits << endl;

    return 0;
}
like image 613
I ate some tau Avatar asked May 07 '26 13:05

I ate some tau


1 Answers

The easiest (and C-friendly) way to do what you're trying to is to employ a pointer to char and use it to access the individual bytes of the float variable:

unsigned char *b = (unsigned char *)&number;

Then iterate over the bytes:

for (i = 0; i < sizeof number; i++)
{
    printf("%02x", b[i]);
}

Note that this approach prints out a hexadecimal value, but that's directly convertible to a binary representation if you really want to do it that way:

for (i = 0; i < sizeof number; i++)
{
    for (j = 0; j < CHAR_BIT; j++)
    {
        printf("%d", (b[i] >> j) & 1);
    }
}
like image 191
Carl Norum Avatar answered May 10 '26 01:05

Carl Norum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!