Bit manipulation aka madness

void bitcopy(void *desti, int id, void *source, int is, unsigned n);

I am supposed to make a function (bitcopy) that will copy 'n' bits from address 'source' starting from the 'is'-th bit, to the address 'desti' from the 'id'-th bit. This probably doesn't make any sense so here is an example:

short int a=20500; // 01010000 00010100b
short int b=11231; // 00101011 11011111b
bitcopy(&a,3,&b,4,9);

So we have to copy 9 bits from b.
We start at the 4th(is=4) bit 001 010111101 1111
Now we want to copy the bold section in "a" ,starting from the 3rd(id=3) bit.
So a will now be: 0101010111101100

I need some tips to get started with this. To manipulate the bits I have to use bit operations. ( ^ & | << >> ~ ) How would you make a mask to copy the desired bits? how would you modify "a" with this mask? :icon_confused:

Comments

  • As for the basics, you make a mask to copy the desired bits by making one with binary value 1 for the bits you want. i.e. use 00001111 if you want those four bits of a number. You can construct 00001000 (the byte with value 8) using (1 << 3). You could construct 00001100 with (1 << 3) | (1 << 2). Or you could think of more clever ways.
  • Rashakil wrote:
    As for the basics, you make a mask to copy the desired bits by making one with binary value 1 for the bits you want. i.e. use 00001111 if you want those four bits of a number. You can construct 00001000 (the byte with value 8) using (1 << 3). You could construct 00001100 with (1 << 3) | (1 << 2). Or you could think of more clever ways.
    For the example I gave let's say I build the mask and extract these bits:
    000 010111101 0000 . How do I insert them in a=010 100000001 0100 ?
    My first thought is to delete those bits from 'a' with this mask 111 000000000 1111 :
    010 100000001 0100 & 111 000000000 1111 = 010 000000000 0100
    And then simply
    010 000000000 0100 | 000 010111101 0000 = 010 010111101 0100 The output i want.

    However this is crazy! I need to make the masks on the spot! For any kind of INPUT! :sweat:
  • codemylife wrote:
    However this is crazy! I need to make the masks on the spot! For any kind of INPUT! :sweat:

    :rolleyes: build one bit by bit using a loop, or think of something more clever.
  • I will think of something clever just you wait. Something clever...yes something clever...something clever...really clever....hmmm
  • ^ lol.

    As Rashakil said, just start simple and use a for loop.

    Are there any restrictions on 'n', 'is', or 'id'? If they can be something large, like say, 200, you're going to need a loop anyways.

    But in the simple case, just think about how to iterate over the bits that you want, isolating them one at a time, and then modifying the respective bit in the 'dest'. Then try to make improvements afterward.
  • I love these kind of assignments.

    Like Sane said, you will probably need to use a loop.
Sign In or Register to comment.