#include <Arduino.h>
int findFirstOneBitPosition(const uint8_t* bytes, size_t length)
{
// Step 1: Concatenate all bytes into a single large number representation
uint32_t combinedNumber = 0;
Serial.println(" ==================> Inside (findFirstOneBitPosition) function:");
for (int i = 31; i >= 0; --i)
{
Serial.print("bytes[");
Serial.print(i);
Serial.print("] = ");
Serial.print(bytes[i]);
Serial.print(", -----> bytes[");
Serial.print(bytes[i]);
Serial.print("] << (");
Serial.print(i);
Serial.print(" * 8) = ");
Serial.println((uint32_t (bytes[i])) << (i * 8),BIN);
combinedNumber += uint32_t (bytes[i]) << (i * 8);
}
Serial.println(" ==================> End of (findFirstOneBitPosition) function");
Serial.print("Combined Number = ");
Serial.print(combinedNumber);
Serial.print(" = HEX = ");
Serial.print(combinedNumber, HEX);
Serial.print(" = BIN = ");
Serial.println(combinedNumber, BIN);
uint32_t minuscombinedNumber = -combinedNumber;
Serial.print("-Combined Number = ");
Serial.print(minuscombinedNumber);
Serial.print(" = HEX = ");
Serial.print((minuscombinedNumber), HEX);
Serial.print(" = BIN = ");
Serial.println(minuscombinedNumber, BIN);
// Step 2: Isolate the first 1 bit from the right
uint32_t isolatedBit = combinedNumber & minuscombinedNumber;
Serial.print("Step 2: Isolated Bit = ");
Serial.println(isolatedBit);
// Step 3: 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));
Serial.print("Step 3: Position of isolated bit = ");
Serial.println(position);
return position;
}
void setup()
{
// Initialize serial communication at 9600 bits per second
Serial.begin(9600);
// Example 32-byte array representing a number
// The number should be saved and printed in using Little Endian method ----------> This is an important note, which made to us a waste a lot of times
uint8_t binaryArray[32] = {0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
Serial.print("Binary Array:");
for (int i = 31; i >= 0; --i)
{
Serial.print(binaryArray[i], BIN);
Serial.print(" ");
}
Serial.println(" ");
// Find the position of the first 1 bit from the right
int position = findFirstOneBitPosition(binaryArray, 32);
// 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
}