Last active
August 29, 2015 14:12
-
-
Save YetAnotherMinion/039578f62733ad2f8393 to your computer and use it in GitHub Desktop.
Using structs and unions to bitwise slice a builtin type
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 <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