epiphany
epiphany

Reputation: 766

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

Upvotes: 0

Views: 517

Answers (2)

Axel Podehl
Axel Podehl

Reputation: 4303

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++?

Upvotes: 1

Swift - Friday Pie
Swift - Friday Pie

Reputation: 14614

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.

Upvotes: 2

Related Questions