Reverse hex value

Jul 22, 2011 at 1:11pm
Hi

I have a binaray file that is read in to a char vector. The problem is that the values that im interested in are somehow reversed.

cout << hex << static_cast<int>(myVector[4]) << endl;

The value from the vector formatted as hex is for example 87, but i want it reversed to 78.
Is that possible, if so could someone give me a hint.
Jul 22, 2011 at 2:35pm
I'm afraid what you observe is only a part of the iceberg. It's probably not as simple as "reversed".
The real mechanism, I believe, is the following:
you read data into memory in char, i.e. byte, 8 bits. You memory is byte addressed. Then you do a type cast when outputing the values in the vector. The new type is int, i.e. 32 bit (might not be true on all machines, but very likely to be true). So you program is outputing four bytes of binary values at a time.

As to reversing the observed 87 into 78, you might want to look into your program and find out the real reason. Simply doing a reverse is easy, but you need a good reason to support your reverse.
Jul 22, 2011 at 5:04pm
Endianness.
Jul 22, 2011 at 5:07pm
Ok, thanks!!

I suspected it was not that easy and i have to look into it more thoroughly and do it right.

For now i could need some help with just doing a reverse. You say it is easy, can you give me an example, i would really appreciate it.
Jul 22, 2011 at 5:42pm
Endianness.

I suspected that too and that is a mess ;-)
Jul 22, 2011 at 5:46pm
@Fredic:

I don't know why you want this, but:
temp = static_cast<int>(myVector[4]);
cout << hex << (temp -16*6)*16+6;
Jul 22, 2011 at 5:58pm
Thank you very much!! :-)
Jul 22, 2011 at 7:19pm
It's all right. Are you trying to convert numbers in hex?
If that's the case:

78 in hex means: 7*16^1 + 8*16^0.


Assume 0x78 is A in decimal, then:
A/16 gives you 7;
A - 7*16 gives you 8


Jul 22, 2011 at 9:02pm
Because no one mentioned it yet, if it is endianness, it would not become 87 --> 78. If that is what's happening, than it is not endianess. It would do more of the following style:
1
2
00 00 00 87 //before
87 00 00 00 //after  


In that particular case, it would go from a positive value very close to 0, to more then halfway to the max negative value.
Topic archived. No new replies allowed.