Home > other >  How to find the leftmost 6 bits of a number
How to find the leftmost 6 bits of a number

Time:02-23

I am working on a project and it asks me to find the instruction and register from the given input using bit operators. For example:

Given: 0x316ac000 => The output will be lt R5 R10 R11

R: represent the register

I tried to convert it on paper. The way I did it was first convert that input to binary (ignore the 0x), then I group the left most 6 bits which give me a decimal = 12, 12 is sub base on the table.

So how can I actually code it? or the logic on this

Thank you for your help! enter image description here

enter image description here

CodePudding user response:

Binary is a notation for humans.

To get bits from a number, use the bit shift and bit mask operations. For example, to get bits 3-5 of a value:

(value >> 3) & 0x7

That is, shift right three bits (to get rid of bits 0, 1, and 2) and bit mask (logical AND) with a 7, which equals 0x111.

You can compute a mask by a bit shift and subtract:

(1 << N_bits) - 1

So we can write a function:

unsigned long get_bits( int start, int stop, unsigned long value )
{
  unsigned long mask = (1UL << (stop - start   1)) - 1;
  return (value >> start) & mask;
}

BTW, bit shifts are tricky with integers. Use unsigned values.

  •  Tags:  
  • c
  • Related