Reputation: 35
Say I have these 8 bit chars:
01111111 00011100 01101111
I want to omit the leading 0 and append the bits from char before like so:
11111110 01110011 01111000
*note that the last char has been padded with zeros.
Any advice on how to do this would be much appreciated. cheers.
Upvotes: 2
Views: 76
Reputation: 11546
Shift the first char up 1:
num[0] << 1;
This will turn 01111111
into 11111110
. Now you need to OR the LSB with the MSB of the next char. To do that you need a shifted copy of the next char:
char copy = num[1] >> 7;
This would turn 01110011
into 00000000
, since it's high bit was 0. You can now OR the two:
num[0] |= num[1];
Which will give you what you want.
To do this with a sequence, you would need to loop and increase the shifts at each iteration up to 8, then reset.
Note that as chux points out, you are best off using unsigned types for stuff like this.
Upvotes: 3