Created
February 12, 2014 22:04
-
-
Save akoluthic/8965473 to your computer and use it in GitHub Desktop.
Bit twiddling method for breaking up a byte into 4 2-bit sections
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 <stdint.h> | |
int main() { | |
//set initial vars, range of 0 - 3 | |
int p1 = 1; | |
int p2 = 2; | |
int p3 = 0; | |
int p4 = 3; | |
//add all 4 to the 8 bit container | |
uint8_t container = p1 | (p2 << 2) | (p3 << 4) | (p4 << 6); | |
//retrieve them by shifting/masking | |
int gp1 = container & 0x3; | |
int gp2 = (container >> 2) & 0x3; | |
int gp3 = (container >> 4) & 0x3; | |
int gp4 = (container >> 6) & 0x3; | |
//test to make sure we got the right numbers back | |
printf("gp1: %d, gp2: %d, gp3: %d, gp4: %d\n", gp1, gp2, gp3, gp4); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment