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.

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

Recommended Answers

All 2 Replies

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;

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.