Riccardo79
Riccardo79

Reputation: 1046

C buffer conversion to int

this snippet

unsigned char len_byte[4+1];
...
for(i=0; i < 4; i++) {
   printf("%02x ", len_byte[i]);
}

prints

8a 00 00 00

I need now to set a integer value to 168 (0x000000a8). Can sameone help me?

Thanks to all, Riccardo

edit, I tried:

uint32_t len_dec=0; 
len_dec += (uint32_t)len_byte[0] | ((uint32_t)len_byte[1]<<8) | ((uint32_t)len_byte[2]<<16) | ((uint32_t)len_byte[3]<<24); 
printf("%" PRIu32 "\n",len_dec);
--> 4522130

Upvotes: 1

Views: 1332

Answers (1)

Gabriel L.
Gabriel L.

Reputation: 5014

With this code, I got 168 as answer :

int main(void) {
    unsigned char len_byte[4] = {0x8a,0,0,0};
    unsigned int len_dec = 0;
    int i;
    for(i = 3; i >= 0; --i)
    {
        len_dec |= ((len_byte[i] >> 4) << (8*i)) | ((len_byte[i] & 0xF) << ((8*i) + 4));
    }

    printf("%lu\n", len_dec);
    return 0;
}

Tested here

The trick is to group each byte by 4 bits. 138 = 10001010 in binary. Grouping by 4 bits, you have 2 groups : 1000 and 1010. Now you swap both groups : 10101000 which gives 168. You do this action for each byte starting at the last element of the array.

Upvotes: 1

Related Questions