Created
October 23, 2019 02:55
-
-
Save juliendkim/6281f3368f2074f4125420460cdbde78 to your computer and use it in GitHub Desktop.
How variables are represented in memory
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 <stdlib.h> | |
#define MEM_TO_BIN(obj) mem_to_bin((char[sizeof(obj) * 9 + 1]){""}, &(obj), sizeof(obj)) | |
char *mem_to_bin(char *buffer, void *object, size_t sizeof_object) { | |
const unsigned char *p = (const unsigned char *)object; | |
p += sizeof_object; | |
char *s = buffer; | |
while (sizeof_object-- > 0) { | |
unsigned bits_per_byte = 8; | |
p--; | |
while (bits_per_byte-- > 0) | |
*s++ = ((*p >> bits_per_byte) & 1) + '0'; | |
*s++ = ' '; | |
} | |
*s = '\0'; | |
return buffer; | |
} | |
int main(void) { | |
int i = 1; | |
printf("[%20d]\n%s\n", i, MEM_TO_BIN(i)); | |
float f = 3.14; | |
printf("[%20.5f]\n%s\n", f, MEM_TO_BIN(f)); | |
double d = 3.14; | |
printf("[%20.5f]\n%s\n", d, MEM_TO_BIN(d)); | |
{ | |
char data[20] = "Hello World!!"; | |
printf("[%s]\n", data); | |
for (int i = 0; i < sizeof(data); i++) { | |
if(i % 5 == 0 && i) printf("\n"); | |
printf("%s", OBJ_TO_BIN(data[i])); | |
} | |
printf("\n"); | |
} | |
{ | |
char data[4][5] = {"Go", "Good", "Hi!"}; | |
for(int i = 0; i < sizeof(data) / sizeof(data[0]); i++) { | |
printf("[%s]\n", data[i]); | |
for(int j = 0; j < sizeof(data[i]); j++) { | |
if(j % 8 == 0 && j) printf("\n"); | |
printf("%s", OBJ_TO_BIN(data[i][j])); | |
} | |
printf("\n"); | |
} | |
} | |
return 0; | |
} | |
=========================================== | |
OUTPUT | |
=========================================== | |
[ 1] | |
00000000 00000000 00000000 00000001 | |
[ 3.14000] | |
01000000 01001000 11110101 11000011 | |
[ 3.14000] | |
01000000 00001001 00011110 10111000 01010001 11101011 10000101 00011111 | |
[Hello World!!] | |
01001000 01100101 01101100 01101100 01101111 | |
00100000 01010111 01101111 01110010 01101100 | |
01100100 00100001 00100001 00000000 00000000 | |
00000000 00000000 00000000 00000000 00000000 | |
[Go] | |
01000111 01101111 00000000 00000000 00000000 | |
[Good] | |
01000111 01101111 01101111 01100100 00000000 | |
[Hi!] | |
01001000 01101001 00100001 00000000 00000000 | |
[] | |
00000000 00000000 00000000 00000000 00000000 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment