-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
fb25f8e
commit ce7fd5c
Showing
1 changed file
with
36 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
#include <stdio.h> | ||
#include <stdint.h> | ||
/* Extracting bits from a byte */ | ||
uint32_t extractBits(uint8_t number, int startBit, int endBit) { | ||
startBit = (startBit < 0) ? 0 : (startBit > 8) ? 8 : startBit; | ||
endBit = (endBit < 0) ? 0 : (endBit > 8) ? 8 : endBit; | ||
|
||
|
||
if (startBit > endBit) { | ||
int temp = startBit; | ||
startBit = endBit; | ||
endBit = temp; | ||
} | ||
|
||
|
||
uint8_t bitmask = ((1U << (endBit - startBit + 1)) - 1) << startBit; | ||
|
||
|
||
uint8_t extractedBits = (number & bitmask) >> startBit; | ||
|
||
return extractedBits; | ||
} | ||
|
||
int main() { | ||
uint8_t number = 0b10010101; | ||
|
||
int startBit = 7; | ||
int endBit = 7; | ||
|
||
uint8_t result = extractBits(number, startBit, endBit); | ||
|
||
printf("Original number: 0b%b\n", number); | ||
printf("Extracted bits : 0b%b\n", result); | ||
|
||
return 0; | ||
} |