tags:

views:

221

answers:

5

Hello,

I have to do some work work with integers, but I am interested in treat them as binary data, in a way that for example I can take the 4 most significant bits of an 32 bit value. What I am trying to do is, I have several 32 bit value I want to take for example, in the first one 4 bits, the second one 6 bits and the last one 22 bits, and after concatenate them and get another 32 bits value.

Can anyone please recommend any library or any othe way to do this?. Thank you.

+3  A: 

It seems that you don't need a library for that. Just bit shifting, logical and, or and xor should be sufficient for what you want to do.

EDIT: Just to give an example. Suppose a is a 32-bit int, and you want to take the first 4 bit and store it in the lowest bit positions in another integer b, you could do this:

b = (a & (0xf << (31-4))) >> (31-4)
PolyThinker
+1  A: 

Just use the built in bitwise operators?

int a;
int b;
int c;

int result = a & 0xF0000000 | b & 0x0FC00000 | c & 0x003FFFFF;
Rowland Shaw
+1  A: 

Just try with the bitwise operators to treat them using their bits: |, &, ^, <<, >>.

For IO, if want to guaranty that are all of them readeable by multiple platforms, treat them with htons(), htonl(), ntohs(), ntohl() function set.

daniel
A: 

There are several existing articles on bit operations, Absolute Beginner’s Guide to Bit Shifting? or Explanation of an algorithm to set, clear and test a single bit.

bortzmeyer
A: 

I always prefer to use bit-fields and let the compiler figure out all the bit shifts. It also makes it easier if you ever want to make a change. However, you have to be careful with signed integers and understand how the compiler treats them with respect to bitfields.

Nonetheless...

union _type
{
    struct
    {
        unsigned int a : 22;
        unsigned int b : 6;
        unsigned int c : 4;
    };

    unsigned int u;
    int          s;
};
gatorfax