Join our subscribers list to get the latest news, updates and special offers directly in your inbox
Overview
Finding the Maximum Number of Consecutive Set Bits in a Byte Array
This blog post will delve into a C program designed to find the maximum number of consecutive set bits (bits with a value of 1) within an array of bytes.
Understanding the Code :
#include "stdio.h" #include "stdint.h" uint32_t findMaxNumberOfSetBits(uint8_t *arr, size_t size) { uint32_t maxSetBitsCount = 0; uint32_t currentSetBitsCount = 0; for (size_t i = 0; i < size; ++i) { uint8_t byte = arr[i]; while (byte) { if (byte & 1) { ++currentSetBitsCount; } else { maxSetBitsCount = (currentSetBitsCount > maxSetBitsCount) ? currentSetBitsCount : maxSetBitsCount; currentSetBitsCount = 0; } byte >>= 1; } // Check for consecutive 1s at the end of the byte maxSetBitsCount = (currentSetBitsCount > maxSetBitsCount) ? currentSetBitsCount : maxSetBitsCount; currentSetBitsCount = 0; } return maxSetBitsCount; } int main() { uint8_t bytesStream[] = {0x12, 0x34, 0x56, 0x78}; printf("Combined bytes: 0x%04x\n", *(uint32_t*)&bytesStream[0]); printf("Max consecutive set bits: %d\n", findMaxNumberOfSetBits(bytesStream, sizeof(bytesStream))); return 0; }
2. Function Declaration:
3. Function Implementation:
maxSetBitsCount = (currentSetBitsCount > maxSetBitsCount) ? currentSetBitsCount : maxSetBitsCount : Updates maxSetBitsCount with the maximum value between the current currentSetBitsCount and the previous maxSetBitsCount.
4. Main Function:
Bit Stream Equivalent => 00010010 00110100 01010110 01111000
5 . Key Points:
The code effectively iterates through each byte and bit within the array to determine the maximum number of consecutive set bits.The use of bitwise operators (& for bitwise AND and >>= for right shift) is crucial for efficiently manipulating individual bits.The code demonstrates a clear and concise approach to solving this specific problem.
As per byte stream max sets continious bit set is 4.
EmbeddedWala
EmbeddedWala Jun 14, 2023 0 26.4K
EmbeddedWala Apr 27, 2023 0 24.4K
EmbeddedWala Apr 26, 2023 0 21.0K
EmbeddedWala Feb 15, 2024 0 20.4K
EmbeddedWala Aug 30, 2022 0 19.0K
EmbeddedWala Jun 19, 2022 0 5.2K
This site uses cookies. By continuing to browse the site you are agreeing to our use of cookies Find out more here