I want to know the length of the binary form of an integer.
eg for 3 it should return 2 (11)
for 9 it should return 4(1001)
I want to know the length of the binary form of an integer.
eg for 3 it should return 2 (11)
for 9 it should return 4(1001)
Why would you need to do this?
Variable size is always fixed.
To be strictly correct the answer should always be 16 for a 16 bit integer and the answers for 3 and 9 should be 2 and 3, but if you really want to do as you say then something like this (untested)
void setup()
{
Serial.begin(115200);
Serial.println(findHighestBit(0b0000000000000011));
Serial.println(findHighestBit(0b0000000000001001));
Serial.println(findHighestBit(0b0000000000000000));
Serial.println(findHighestBit(0b1000000000000000));
Serial.println(findHighestBit(0b1111111111111111));
}
void loop()
{
}
byte findHighestBit(int x)
{
for (int bit = 15; bit >= 0; bit--)
{
if (bitRead(x, bit))
{
return bit + 1;
}
}
return 0;
}
You could also do it with bit shifting but bitRead() is very convenient
@UKHeliBob thank u that worked fine
harshmittal2210:
@UKHeliBob thank u that worked fine
Like others here I am intrigued as to why you want to do this.
Oh, you can also find it in aritmetical level
while (number)
{
number=number/2;
bit++;
}
Where number is A COPY of the original variable, and bit is a variable visible also out of the while.
I don't know if this method is quicker than the other, but it is a solution.
Google the function "clz" (count leading zeroes) and "ffs" (find first set) functions.
Also, mathematically: ceiling(log2(n))
(It is an amusing thing, to be writing "software" for something like a programmable scientific calculator, which can probably do log2(n) much more quickly than any of the other ways to figure out how many bits a number would take,)