sushant
sushant

Reputation: 41

converting big endian to Little endian

I have a wireshark data whose output looks like this say: "c1 c1 31 ad 1f...". I have stored these values is an array

unit8_t array[10]={0xc1,0xc1,0x31,0xad,0x1f...}

Now I want to convert this array in little endian and store in some other array:

//Sample code to convert to little endian

for(i = 0;i<32;i++)
{
        uint8_t res = ntohs(htons(array[i]));// converting element to little endian
        plain_text_little_endian[i] = res;
}

Just wanted to know, will it convert the value "res" in little endian?

Upvotes: 0

Views: 210

Answers (1)

prog-fh
prog-fh

Reputation: 16785

You apply ntohs() or htons() to a single byte value (uint8_t) but these functions (or macros) consider two-byte values.
Anyway, applying these functions one after each other will not change the value; think about it in the daily life, you swap two objects, and swap them again.

If you want to consider every pair of bytes in array as a 16-bit integer in big-endian order and stored them in host order, maybe should you try this:

uint8_t array[10]={...};
uint16_t output[5];
for(int i=0; i<5; ++i)
{
  output[i]=(uint16_t)((array[2*i+1]<<8)|array[2*i+0]));
}

Upvotes: 2

Related Questions