1

I have a byte, whose value in binary is 11111111. I have to extend my byte to 16 bits 0101010101010101 according to these rules: if bit = 1, now is 01. If bit = 0, now is 10.

For example:

00001111 -> 1010101001010101
00000101 -> 1010101010011001

What is the operation to do this?

samgak
  • 23,944
  • 4
  • 60
  • 82
joao brum
  • 31
  • 1

2 Answers2

1

First, convert your byte to an int:

int x = (int)byte_value;

Then, extend to 16 bits, by shifting bits 4 at a time, then 2, then 1, then doubling each bit with a shift and bitwise OR:

x = ((x << 4) | x) & 0b0000111100001111;
x = ((x << 2) | x) & 0b0011001100110011;
x = ((x << 1) | x) & 0b0101010101010101;
x = (x << 1) | x;

Then, mask the bits so that the even bit positions are 1 if the bit is 1, and the odd positions are 1 if the bit is 0 (using bitwise NOT):

x = (x & 0b0101010101010101) | (~x & 0b1010101010101010);
aka.nice
  • 9,100
  • 1
  • 28
  • 40
samgak
  • 23,944
  • 4
  • 60
  • 82
  • Beware: if ever the byte_value is signed char, then conversion to int will perform sign extension and might populate all but low 8 bits with 1. – aka.nice Feb 14 '17 at 15:18
0

I don't think that there is an operator for "expanding" bits as described. But you could do it in a loop together with shifting and testing bits as follows:

unsigned char b = 0xff;
unsigned int result = 0x0;

for (int i=0; i<8; i++) {
    result <<= 2;  // make place for the next 2 bits

    int isSet = b & 0x80; // check highest significant bit of b
    if (isSet) {
        result |= 0x01;  // in bits: 01
    }
    else {
        result |= 0x02; // in bits: 10
    }

    b <<= 1;
}

Hope it helps.

Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58