Ralph Shillington Ralph Shillington - 2 months ago 5x
C# Question

How to set endianness when converting to or from hex strings

To convert an integer to a hex formatted string I am using ToString("X4") like so:

int target = 250;
string hexString = target.ToString("X4");

To get an integer value from a hex formatted string I use the Parse method:

int answer = int.Parse(data, System.Globalization.NumberStyles.HexNumber);

However the machine that I'm exchanging data with puts the bytes in reverse order.

To keep with the sample data, If I want to send the value 250 I need a string of "FA00" (not 00FA which is what hexString is) Likewise if I get "FA00" I need to convert that to 250 not 64000.

How do I set the endianness of these two converstion methods?


That isn't an inbuilt option. So either do string work to swap the characters around, or so some bit-shifting, I.e.

int otherEndian = (value << 16) | (((uint)value) >> 16);