Last active
January 16, 2020 05:36
-
-
Save nobane/7f601430e1581497d3ab314a440054d4 to your computer and use it in GitHub Desktop.
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> | |
#include <string.h> | |
// prints out the binary representation of i | |
void print_bits(int i) { | |
int mask = (1 << 1) - 1; | |
int bit = 0; | |
printf("0x%08X is\n", i); | |
// reverse loop pulling out one bit at a time | |
for (int x = 31; x > -1; x--) { | |
if (x == 30 || x == 22) { | |
printf(" "); | |
} | |
bit = (i >> x) & mask; | |
printf("%i", bit); | |
} | |
printf("\n"); | |
// print out some nice lines | |
for (int x = 0; x < 32; x++) { | |
if (x == 1 || x == 9) { | |
printf(" "); | |
} | |
printf("-"); | |
} | |
printf("\ns exp frac\n\n"); | |
} | |
// turns string of bits into an int (starting from right side) | |
void print_num(const char* bits) { | |
int num = 0; | |
char str[] = "0"; | |
int place = 0; | |
// forward loop over the string to print out the bits | |
for (int x = 0; x < strlen(bits); x++) { | |
if (bits[x] == ' ') continue; | |
printf("%c", bits[x]); | |
} | |
// reverse loop over the bits, use OR op to set bits of num | |
for (int x = strlen(bits) - 1; x < 31 - strlen(bits); x--) { | |
if (bits[x] == ' ') continue; | |
str[0] = bits[x]; | |
num ^= (-atoi(str) ^ num) & (1UL << place); | |
place++; | |
} | |
printf(" is \n0x%08X\n\n", num); | |
} | |
int main() { | |
print_bits(0x1); | |
print_bits(0x2); | |
print_bits(0x3); | |
print_bits(0xC0400001); | |
print_bits(0xdeadbeef); | |
print_bits(0xffffffff); | |
// bits will start on the right side | |
// spaces are ignored | |
print_num( "111"); | |
print_num("0 00000000 00000000000000000000001"); | |
print_num("1 00000000 00000000000000000000001"); | |
print_num("1 00000000 00000000000000000000000"); | |
print_num("1 10000000 10000000000000000000001"); | |
print_num("1 11111111 11111111111111111111111"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment