0

I want to copy certain number of bits from a variable to certain position in another variable Example: I have 8 bit of data. I want to extract higher 4 bits of this byte and transfer them to a 32 bit data variable from bit position 19. How best this can be accomplished? I tried following, but does not seem to be working. instead of 19, I should be able to copy to even from zero position.

int bitPos=19;   // Position where the extracted data needs to be copied
int var1; //32 bit data
unsigned char testByte;
testByte&=0xF0;   // Lower nibbles not needed
testByte=testByte>>4; // Get only higher nibble
var1|=testByte<<bitPos;
Mahesha Padyana
  • 431
  • 6
  • 22
  • 1
    `testByte< – wimh Jun 07 '15 at 18:56
  • `unsigned char` is not large enough for `19 bits`. also you need to clear `19-22` bits of `var1` before you do the `|`. – Arjun Sreedharan Jun 07 '15 at 19:11
  • *"I tried following, but does not seem to be working..."* - How is it not working? – jww Jun 07 '15 at 21:49
  • In general you must be aware of how implicit type promotions work: what they do and what they don't. `testByte` in your case will get integer-promoted to an `int`, which is a signed type, possibly too small, and probably not be what you want. It may work by luck in this case. Serious programmers would use self-documenting code and write `testByte = (uint32_t)testByte >> 4;` just to show that 1) they actually know about implicit integer promotions and 2) have considered them in this code. – Lundin Jun 08 '15 at 09:54
  • (So if you posted a comment saying "you can't shift an unsigned char 19 bits" without evening mentioning the implicit promotion taking place in this code, you are likely among those who also need to learn about [implicit type promotions](http://stackoverflow.com/questions/17312545/type-conversion-unsigned-to-signed-int-char).) – Lundin Jun 08 '15 at 09:57

1 Answers1

1

I tried to run your code, it seems to be working. For testbyte = 64, I got var1 = 2097152.

May be int is not 32 bit for your platform, I can't think of any other reason.

Apoorv
  • 85
  • 1
  • 7