Reputation: 316
I have a char buffer with 4 numbers, in binary:
buffer[0] = 00000000
buffer[1] = 00000000
buffer[2] = 00000000
buffer[3] = 00000001
I want to "fetch" the 4 bytes of the buffer and create a long int.
In this case, the long int variable would be:
test == 00000000 00000000 00000000 00000001
This is my code but I have the feeling that it is conceptually wrong:
int main() {
unsigned char buffer [4];
buffer[0] = 0;
buffer[1] = 0;
buffer[2] = 0;
buffer[3] = 1;
for (int i = 0; i < 4; i++)
printf ("%d\n", buffer[i]);
long int * addr = (long int *) &buffer[0];
long int test = * addr;
printf ("test = %li\n", test);
}
Output:
0
0
0
1
test = 140728915197952
I was trying to use pointers because I think it's the right way but I don't understand myself at all.
My machine is LittleEndian
if can help.
Upvotes: 2
Views: 911
Reputation: 493
You can use left shift with bitwise or in the loop, like this:
uint32_t l = 0;
for(int i=0;i<4;i++){
l<<=8;
l|=buffer[i];
}
printf("l=%x\n",l);
Shift and Bitwise operations are typically very fast in all processors.
Suggestion: int, long may have different size. To ensure 32bit size, please use uint32_t instead.
Upvotes: 4
Reputation: 141618
The code could be:
#include <inttypes.h>
// ...
uint32_t test = buffer[0] * 0x1000000u + buffer[1] * 0x10000u + buffer[2] * 0x100u + buffer[3];
printf("test = " PRIu32 "\n", test);
It would be a good idea to use a fixed width type for this scenario , because unsigned long
might have different sizes on different platforms .
Upvotes: 2