I am trying to access the individual bytes in a floating point number and I am getting unexpected results

Posted by oweinh on Stack Overflow See other posts from Stack Overflow or by oweinh
Published on 2014-06-08T03:06:07Z Indexed on 2014/06/08 3:24 UTC
Read the original article Hit count: 125

Filed under:
|

So I have this so far:

#include <iostream>
#include <string>
#include <typeinfo>

using namespace std;

int main ()
{
    float f = 3.45;           // just an example fp#
    char* ptr = (char*)&f;    // a character pointer to the first byte of the fp#?

    cout << int(ptr[0]) << endl; // these lines are just to see if I get what I 
    cout << int(ptr[1]) << endl; // am looking for... I want ints that I can 
    cout << int(ptr[2]) << endl; // otherwise manipulate.
    cout << int(ptr[3]) << endl;
}
the result is:
-51
-52
92
64

so obviously -51 and -52 are not in the byte range that I would expect for a char... I have taken information from similar questions to arrive at this code and from all discussions, a conversion from char to int is straightforward. So why negative values? I am trying to look at a four-byte number, therefore I would expect 4 integers, each in the range 0-255.

I am using Codeblocks 13.12 with gcc 4.8.1 with option -std=C++11 on a Windows 8.1 device.

© Stack Overflow or respective owner

Related posts about c++

Related posts about floating-point