oweinh
oweinh

Reputation: 15

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

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.

EDIT: So the solution was to use:

unsigned char* ptr = reinterpret_cast<unsigned char*>( &f );

Thank you for all the responses.

Upvotes: 0

Views: 114

Answers (1)

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145419

Use unsigned char in order to get (guaranteed) unsigned values.

You're getting negative values because with your compiler and compiler options (yes, that matters) char is a signed type.


By the way, the prefix + operator is a handy, concise way to promote a char to int, for the purpose of displaying the numerical value.


Also, by the way, it's a generally good idea to use a C++ named casts (reinterpret_cast, const_cast, static_cast and dynamic_cast) instead of C style casts, where pointers are concerned. That's because a C style cast can end up doing something unexpected, especially when the code is maintained and types changed. In this case you are expressing a reinterpret_cast, so that's the one to use – just for good habit's sake.

Upvotes: 6

Related Questions