19172281
19172281

Reputation: 237

Append bits to beginning and end of 10-bit integer

The SPI device I'm using needs 4 bits appended to the left of a 10-bit value, and 2-bits appended to the right.

For example, suppose you have a 10-bit value:

0110100110 - or 422

We want to add 0110 to the left side, and 00 to the right side.

So the result would be:

0110011010011000

How would I do this?

Upvotes: 0

Views: 2210

Answers (2)

Sean
Sean

Reputation: 101

A simple way to do this would be to shift the bits to their desired positions and use the OR operator ( | ) to combine the bits.

int num = 0b0110100110;    
int left_bits = 0b0110;
int right_bits = 0b00;

int result = (left_bits << 12) | (num << 2) | right_bits 

Upvotes: 2

19172281
19172281

Reputation: 237

I think I've found what seems to be a good solution.

As the appended bits are always the same value, and in the same position, I declare an int of 6000.

I then shift the 10-bit value to the left by 2, and or the two together.

int x = 0x6000;
int y = 0xDB << 2;

int result = x ^ y;

Upvotes: -1

Related Questions