#include <Arduino.h>
int findFirstOneBitPosition(uint8_t n)
{
// Step 1: Isolate the first 1 bit from the right
uint8_t isolatedBit = n & -n; // making AND operation between the number and its two's complement gives the us the bit position of the first one (1) bit
Serial.print("Step 1: Isolated Bit = ");
Serial.println(isolatedBit);
// Step 2: Find the position of the isolated bit (1-based index)
// Use precomputed log2 value (1.44269504089) for efficiency
int position = round(log(isolatedBit) * 1.44269504089) + 1;
Serial.print("Step 2: Position of isolated bit = ");
Serial.println(position);
return position;
}
void setup()
{
// Initialize serial communication at 9600 bits per second
Serial.begin(9600);
// Example binary number
uint8_t binaryNumber = 0b1000100;
Serial.print("Binary Number = ");
Serial.println(binaryNumber);
// Find the position of the first 1 bit from the right
int position = findFirstOneBitPosition(binaryNumber);
// Print the position
Serial.print("The position of the first 1 bit (from the right) is: ");
Serial.println(position);
}
void loop() {
// Nothing to do here
}