Well... My issue comes up from having to load big-endian floats from a file. I can load an unsigned integer easily using this function:
1 2 3 4 5
|
unsigned int getIntFromChars(unsigned char* arr)
{
unsigned int x=(arr[0]<<24)|(arr[1]<<16)|(arr[2]<<8)|arr[3];
return x;
}
|
Now... Bit shifting and bitwise operations, as far as I'm concerned, are only really useful on unsigned types, because otherwise you run into signed bit shifting and implicit casting issues.
I've read that "reinterpret_cast" should never ever be used. The official specs say "Misuse of the reinterpret_cast operator can easily be unsafe. Unless the desired conversion is inherently low-level, you should use one of the other cast operators." It also says that reinterpret cast is nonportable at best.
Also, from what I understand, this line:
int n=*(reinterpret_cast<int*>(&x))
is equivalent to the c-style cast:
int n=*((int*)(&x))
due to how c-style casting works (implicitly assuming one of the *_cast operators)
So... what Im asking is... is the following bad code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
unsigned int parseBigEndianUInt(unsigned char* arr)
{
unsigned int x=(arr[0]<<24)|(arr[1]<<16)|(arr[2]<<8)|arr[3];
return x;
}
int parseBigEndianInt(unsigned char* arr)
{
unsigned int x=parseBigEndianUInt(arr);
int n=*(reinterpret_cast<int*>(&x));
return n;
}
float parseBigEndianFloat(unsigned char* arr)
{
unsigned int x=parseBigEndianUInt(arr);
float n=*(reinterpret_cast<float*>(&x));
return n;
}
|
and if it is... what's one supposed to do to edit the bitwise values of types?