Skip to content

Instantly share code, notes, and snippets.

@rshepherd
Last active December 23, 2015 15:29
Show Gist options
  • Save rshepherd/6655719 to your computer and use it in GitHub Desktop.
Save rshepherd/6655719 to your computer and use it in GitHub Desktop.
Interpreting bit patterns as different types
#include<iostream>
using namespace std;
int main() {
//long x = 1;
long x = -1;
// A pointer to the bit pattern, interpreted as a 32-bit signed int
int* i = (int*) &x;
cout << "Bit pattern interpreted as a int:\t\t" << *i << endl;
// A pointer to the bit pattern, interpreted as a 64-bit signed long
long* l = (long*) &x;
cout << "Bit pattern interpreted as a long:\t\t" << *l << endl;
// A pointer to the bit pattern, interpreted as an double
double* d = (double*) &x;
//cout.precision(500);
cout << "Bit pattern interpreted as a double:\t\t" << fixed << *d << endl;
// A pointer to the bit pattern, interpreted as a 32-bit unsigned int
unsigned int* u = (unsigned int*) &x;
cout << "Bit pattern interpreted as an unsigned int:\t" << *u << endl;
}
@rshepherd
Copy link
Author

A demonstration that a value is a bit pattern that we interpret through types. Done in C++ because this is not possible in Java.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment