Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BitConverter VS ToString for Hex

Just wondering if someone could explain why the two following lines of code return "different" results? What causes the reversed values? Is this something to do with endianness?

int.MaxValue.ToString("X") //Result: 7FFFFFFF
BitConverter.ToString(BitConverter.GetBytes(int.MaxValue)) //Result: FF-FF-FF-7F
like image 394
Maxim Gershkovich Avatar asked Dec 16 '22 13:12

Maxim Gershkovich


1 Answers

int.MaxValue.ToString("X") outputs 7FFFFFFF, that is, the number 2147483647 as a whole.

On the other hand, BitConverter.GetBytes returns an array of bytes representing 2147483647 in memory. On your machine, this number is stored in little-endian (highest byte last). And BitConverter.ToString operates separately on each byte, therefore not reordering output to give the same as above, thus preserving the memory order.

However the two values are the same : 7F-FF-FF-FF for int.MaxValue, in big-endian, and FF-FF-FF-7F for BitConverter, in little-endian. Same number.

like image 186
user703016 Avatar answered Jan 06 '23 05:01

user703016