Created
May 28, 2023 18:46
-
-
Save rahji/0df13c0cf4cbe3939f28e2371acdc3aa to your computer and use it in GitHub Desktop.
Left shift bits within 6 bits of a byte, wrapping at the end
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
#include <stdio.h> | |
#include <stdlib.h> | |
// shift bits to the left, while wrapping | |
// but only wrap within the 6 LSBs (ignore the 2 MSBs) | |
unsigned char shift_bit(unsigned char theByte); | |
int main(int argc, char **argv) { | |
if (argc != 2) { | |
printf("Usage: %s <byte>\n", argv[0]); | |
return 1; | |
} | |
unsigned char bytee = atoi(argv[1]); | |
char buffer[33]; | |
itoa(bytee, buffer, 2); | |
printf("Byte before shifting: %s\n", buffer); | |
bytee = shift_bit(bytee); | |
itoa(bytee, buffer, 2); | |
printf("Byte after shifting: %s\n", buffer); | |
return 0; | |
} | |
// Function to shift a bit | |
unsigned char shift_bit(unsigned char theByte) { | |
unsigned char bit; | |
// bit = (theByte & 0x80) >> 7; // Extract the leftmost bit | |
bit = (theByte & 0x20) >> 5; // Extract the leftmost bit (within the 6 LSBs) | |
theByte = (theByte << 1) | bit; // Shift left and OR with the extracted bit | |
return theByte & 0x3F; // Mask the 2 MSBs to 0 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment