-2

For example, I have two digit bits:

0b0111111
0b0000110

I want to shift a state variable by 7 digits and combine them together.

0b00001100111111

Can I accomplish by shifting?

Chris
  • 171
  • 1
  • 3
  • 11

4 Answers4

6

You do this by shifting the bottom number left 7 digits, then performing a bitwise OR of the result and the first number.

unsigned int a = 0x3f;
unsigned int b = 0x06;
unsigned int result = (b << 7) | a;
dbush
  • 205,898
  • 23
  • 218
  • 273
0
unsigned char a = 0b00000110;
unsigned char b = 0b01111111;
unsigned short c = (b << 8); // shift everything left 8 bits to set the high bits
c &= 0xFF00; // clear out the lower bits - not necessary in C
c |= a; // set the lower 8 bits
RyanArr
  • 73
  • 6
0
unsigned int X = 0b00111111;
unsigned int Y = 0b00000110;

unsigned int Z = ((X << 7) & 0xFF00) | Y;
programmerj
  • 1,634
  • 18
  • 29
  • This one fails, absolutely. – iBug Feb 22 '18 at 02:45
  • `0xFF00` is not the right mask for a 7-bit value that's been shifted by 7 bits. Not to mention that `Y` is the one that's supposed to get shifted. – user3386109 Feb 22 '18 at 03:28
  • Correct. Someone submitted that answer when I stepped away from my workstation for a few minutes. I think it was my evil twin brother. – programmerj Feb 22 '18 at 12:59
-1
int a = 0b0111111;
int b = 0b0000110;

int combined = (a << 7) | b;
Dai
  • 141,631
  • 28
  • 261
  • 374
  • 4
    I would not use signed ints either – programmerj Feb 22 '18 at 02:33
  • 1
    When shifting left, there is no difference between arithmetic and logical shift. When shifting right, the type of shift depends on the type of the value being shifted. https://stackoverflow.com/questions/7622/are-the-shift-operators-arithmetic-or-logical-in-c#7632 – parvus Feb 22 '18 at 05:25