Skip to content

Instantly share code, notes, and snippets.

@YetAnotherMinion
Last active August 29, 2015 14:12
Show Gist options
  • Save YetAnotherMinion/039578f62733ad2f8393 to your computer and use it in GitHub Desktop.
Save YetAnotherMinion/039578f62733ad2f8393 to your computer and use it in GitHub Desktop.
Using structs and unions to bitwise slice a builtin type
#include <iostream>
using namespace std;
//Custom slicing type
struct Bar {
unsigned fn : 4; //first nibble
unsigned sn : 4; //second nibble
};
//Representation
union Foo {
short a;
Bar b;
};
Foo * bat = new Foo;
bat->a = 30;
cout << "Orginal number: "bat->a << endl;
cout << "First nibble: " << bat->b.fn << endl;
cout << "Second nibble: " << bat->b.sn << endl;
int result = (bat->b.sn)<<4;
result += (bat->b.fn);
cout << "Putting them back together: " << result << endl;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment