0

So let's say I had a set of bits in the following order:

00101 which obviously would be equal to 5

Would it be possible to add a 1 on the left corner of the sets of bits such that it would be 100101 which would be equal to 37. (Using Bit Manipulation)

Thank you very much!

MoveUK
  • 3
  • 1

1 Answers1

0
 00101 which obviously would be equal to 5
100101 which would be equal to 37

To solve this you need two values:

  1. The bit value given above, here named val
  2. The count of bits in the value (because it is not a regular value like 8,16,...), here named len

Then you can get the final value by using the following formula:

result = val | (1 << len)

In your case this would be

result = 00101b | (1 << 5d) = 00101b | 100000b = 100101b

In x86 assembly (Intel MASM syntax) this could be done like this

mov eax, val   ; EAX = 00000101
mov ecx, len   ; ECX = 5
mov edx, 1     ; EDX = 00000001
shl edx, cl    ; EDX = 00100000
or  eax, edx   ; EAX = 00100101
zx485
  • 28,498
  • 28
  • 50
  • 59