Sreram
Sreram

Reputation: 501

Why is the function displaying the hex code in reverse order?

The following code (in C++) is supposed to get some data along with it's size (in terms of bytes) and return the string containing the hexadecimal code. size is the size of the memory block with its location stored in val.

std::string byteToHexString(const unsigned char* val, unsigned long long size)
{
    unsigned char temp;
    std::string vf;
    vf.resize(2 * size+1);
    for(unsigned long long i= 0; i < size; i++)
    {
        temp = val[i] / 16;
        vf[2*i] = (temp <= 9)? '0' + temp: 'A' + temp - 10; // i.e., (10 = 9  + 1)
        temp = val[i] % 16;

        vf[2*i+1] = (temp <= 9)? '0' + temp: 'A' + temp - 10; // i.e., (10 = 9  + 1)
   }

vf[2*size] = '\0';
return (vf);
}

So on executing the above function the following way:

int main()
{
     unsigned int a = 5555;
     std::cout << byteToHexString((unsigned char*)(&a), 4);
    return 0; 
}

The output we obtain is:

B3150000

Shouldn't the output rather be 000015B3? So why is this displaying in reverse order? Is there something wrong with the code (I am using g++ compiler in Ubuntu)?

Upvotes: 1

Views: 1584

Answers (1)

paddy
paddy

Reputation: 63481

You are seeing the order in which bytes are stored for representing integers on your architecture, which happens to be little-endian. That means, the least-significant byte comes first.

If you want to display it in normal numeric form, you either need to detect the endianness of your architecture and switch the code accordingly, or just use a string stream:

unsigned int a = 5555;
std::ostringstream ss;
ss << std::setfill( '0' ) << std::setw( sizeof(a)*2 ) << std::hex << a;
std::cout << ss.str() << std::endl;

Upvotes: 4

Related Questions