Created
July 7, 2020 22:35
-
-
Save nobane/fba4677410267932ada750faeb8fe242 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> | |
void print_bits(int i) { | |
// prints out the binary representation of a 32bit int | |
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"); | |
} | |
void print_num(const char* bits) { | |
int num = 0; | |
int place = 0; | |
char str[] = "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 (or %i as decimal)\n\n", num, num); | |
} | |
int main() { | |
print_bits(0x1); | |
print_bits(0x2); | |
print_bits(0x3); | |
print_bits(0xC0400001); | |
print_bits(0xdeadbeef); | |
print_bits(0x7F7FFFFF); | |
print_bits(0xffffffff); | |
print_bits(0x3E800000); | |
print_bits(0x41300000); | |
print_bits(0x3FC00000); | |
// 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 00000000000000000000001"); | |
print_num("1 11111111 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