Type encoding viewer
Ever wondered how the values of certain scalar types are stored in the memory of your computer? You can figure it out for most common scalar datatypes by using this code snippet.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | /* Open source version of the program from programming exercise 2 (ICCS/CPS) This code snippet will show you how values of certain variable types are actually stored in memory. Warning: use this program on an x86 operating system, otherwise your answers could be different. This code snippet was written by Wesley Stessens (wesley@ubuntu.com) It is released in the Public Domain. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> int main(int argc, char *argv[]) { int i; if (argc != 3) { printf("=======================================================\n" "Usage: %s <type> <value>\n" "(Possible types: int, float, double, bool, long, short)\n" "=======================================================\n", argv[0]); } else { if (strcmp(argv[1], "int") == 0) { int x = atoi(argv[2]); for (i = 0; i < sizeof(int); i++) printf("%02X ", *((unsigned char*)&x + i)); printf("\n"); } else if (strcmp(argv[1], "float") == 0) { float x = atof(argv[2]); for (i = 0; i < sizeof(float); i++) printf("%02X ", *((unsigned char*)&x + i)); printf("\n"); } else if (strcmp(argv[1], "double") == 0) { double x = atof(argv[2]); for (i = 0; i < sizeof(double); i++) printf("%02X ", *((unsigned char*)&x + i)); printf("\n"); } else if (strcmp(argv[1], "bool") == 0) { bool x; if (strcmp(argv[2], "false") == 0 || strcmp(argv[2], "FALSE") == 0 || strcmp(argv[2], "False") == 0 || strcmp(argv[2], "0") == 0) x = false; else x = true; for (i = 0; i < sizeof(bool); i++) printf("%02X ", *((unsigned char*)&x + i)); printf("\n"); } else if (strcmp(argv[1], "long") == 0) { long x = atol(argv[2]); for (i = 0; i < sizeof(long); i++) printf("%02X ", *((unsigned char*)&x + i)); printf("\n"); } else if (strcmp(argv[1], "short") == 0) { short x = atoi(argv[2]); for (i = 0; i < sizeof(short); i++) printf("%02X ", *((unsigned char*)&x + i)); printf("\n"); } else printf("This type is not supported for this exercise.\n"); } return 0; } |







