简体   繁体   中英

How can i reverse the order of hex in c++

To start with, I have a char array that store data

unsigned char dat[3];

memset(dat, 0, sizeof(dat));                    
memcpy(dat, &no, 2);

when I inspect dat, it contain a hex of 0xfd 0x01 as the value of no is 509, the hex should be 0x01 0xfd

I'm wondering should I be concern of the order of the hexadecimal, should I change the order. Many thanks

Your system is little endian. It's hardware dependent and on little endian platform first byte is the least significant one when treated as part of multi-byte value. Look up: https://en.wikipedia.org/wiki/Endianness

Essentially if CPU is little endian, then value 0x12345689 would be represented as set of bytes starting with 0x89. On big endian it's opposite order and on mixed endian it may change during run-time.

The question really is what do you want to do next ? On your current hardware (Little Endian) this is how the system orders bytes of a numeric. The least significant byte comes first: 0xfd 0x01.

In case you really want to swap this byte order, for whatever reason, checkout: How do I convert between big-endian and little-endian values in C++?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM