0

I am reading 4 bytes in binary file and stored in some variable named as *tmpbuf.
i am printing this variable in decimal value like this.
printf("%d",*tmpbuf);

But now what to do is i want to split 4 bytes into two and want to read those separately and saved in another variable. How to do this?

Ex:*tmpbuf=01 00 00 04; decimal value=16777220

Required o/p:
*tmpbuf1=01 00; decimal value=256
*tmpbuf2=00 04 decimal value=4

3
Contributors
2
Replies
3
Views
9 Years
Discussion Span
Last Post by mcriscolo
0

are you trying to do big/little endean swapping?

unsigned char buf2[4];
buf2[0] = buf1[2];
buf2[1] = buf1[3];
buf2[2] = buf1[0];
buf2[3] = buf1[1];

unsigned int x = *(unsigned int*)buf2;
0

You can use memcpy to copy the various parts of one variable (or buffer) to another.

Assuming that tmpbuf has your data (I assumed is was defined as "char *tmpbuf):

char tmpbuf1[2];
char tmpbuf2[2];

memcpy(&tmpbuf1, &tmpbuf[0], 2);
memcpy(&tmpbuf2, &tmpbuf[2], 2);

The variables tmpbuf1 an tmpbuf2 will contain the data split as you described.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.