2

I've done some digging and I didn't find a solution to my question yet. I want to take a decimal number and turn it into bits. Then i want to analyze the bits and determine the highest bit. For example, 8 is represented as 1000 in binary. The most significant bit is in the 2^4 position. The best solution I have found is to do something like

int temp=8;
bitset<32> binary;
binary=temp;
int pos;

for (int i=32;i>=0;i--){
if (binary[i]==1) {
pos=i;
break;  
}
}

but I am wondering if there is any better solution to this? Is there a way to not include the leading zeros and just have the binary number be 1000 instead of 00....1000? The value in temp could be any number containing 32 bits.

randy
  • 17
  • 1
  • 3
  • 1
    Yeah, that question was from seven years ago. I guess that in the last 7 years, bitwise arithmetic has become a lost art... – Sam Varshavchik Mar 08 '16 at 03:21
  • For any uintXX_t, I have a C++ demo ready which performs a 'binary search' style effort. It finds the most-significant uint64_t bit in 7 steps, and the uint8_t bit in 4 steps. Returns an int index, does not modify the input, 4 ctors lets the user choose the shortest effort with type. Let me know if you have opened a new question. I am glad to submit it.. – 2785528 Mar 11 '16 at 20:53

1 Answers1

1

Assumptions : unsigned numbers only

to calculate MSB of the number you need to know how many bits represent integer part of the number.

if your number is greater than or equal to (2^n/2) where n is number of bits for integer part of number then your MSB will be 1 otherwise it will be 0

please verify the assumption , the logic will be slightly different for signed integers and even more complex for floating point of fixed point floats

  • i am assuming unsigned integers. Im not sure i follow you though. All integers are 32 bits so depending on how large the integer is, the MSB will move positions from 0-31. The MSB will always be 1, it just depends on where at in the integer it is. The leading zeros don't matter. – randy Mar 08 '16 at 03:45