How to set endianness when converting to or from hexadecimal strings

To convert an integer to a hexadecimal formatted string, I use ToString ("X4") as follows:

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

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

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

However, the machine I am exchanging data with puts the bytes in the reverse order.

To save sample data, if I want to send the value 250, I need the string "FA00" (not 00FA, which is hexString). Similarly, if I get "FA00", I need to convert this value to 250 64000.

How to establish the finiteness of these two conversion methods?

+3
source share
2 answers

. , , , I.e.

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

Marc , , , OP. , . , , , Marc. - , 16 .

:

int target = 250; // 0x00FA

// swap the bytes of target
target = ((target << 8) | (target >> 8)) & 0xFFFF;

// target now is 0xFA00
string hexString = target.ToString("X4");

, , 16- , 32- int. 16- ( 16 , <<).

32- :

int target = 250; // 0x00FA

// swap the bytes of target
target = (int)((int)((target << 24) & 0xff000000) |
    ((target << 8) & 0xff0000) |
    ((target >> 8) & 0xff00) |
    ((target >> 24) & 0xff));

// target now is 0xFA000000
string hexString = target.ToString("X8");

, , , . << 24 int , , 0xff000000 uint (UInt32) & long (Int64). |.


, , , .NET , : HostToNetworkOrder() NetworkToHostOrder(). " " "big-endian", "host order" - , , .

, , , NetworkToHostOrder(). , , big-endian, HostToNetworkOrder().

: Int16, Int32 Int64 ( #, short, int long ). , , . :

int target = 250; // 0x00FA

// swap the bytes of target
target = IPAddress.HostToNetworkOrder((short)target) & 0xFFFF;

// target now is 0xFA00
string hexString = target.ToString("X4");

, , short, , 32 . 15 (.. 0x8000), int 16 . , (, short, , 16- ).

, , HostToNetworkOrder() NetworkToHostOrder(), , . , . , .NET NetworkToHostOrder() HostToNetworkOrder(). , , , .NET API API- BSD, , htons() ntohs(), API, , , , .


† , big-endian & hellip, . , , , , , .

+2

Source: https://habr.com/ru/post/1789017/


All Articles