Skip to content

Instantly share code, notes, and snippets.

@rahji
Created May 28, 2023 18:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rahji/0df13c0cf4cbe3939f28e2371acdc3aa to your computer and use it in GitHub Desktop.
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
#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