Created
November 19, 2015 02:35
-
-
Save owlfox/4593f74404cac0123cb6 to your computer and use it in GitHub Desktop.
Show hex, bin, unsigned, signed content of a integer. *This is the helper program modified from code from CSAPP website.
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
/* Display value of fixed point numbers */ | |
#include <stdlib.h> | |
#include <stdio.h> | |
#include <string.h> | |
/* Extract hex/decimal/or float value from string */ | |
static int get_num_val(char *sval, unsigned *valp) { | |
char *endp; | |
/* See if it's an integer or floating point */ | |
int isbinary = 0; | |
int ishex = 0; | |
int isfloat = 0; | |
int i; | |
for (i = 0; sval[i]; i++) { | |
switch (sval[i]) { | |
case 'b': | |
case 'B': | |
isbinary = 1; | |
break; | |
case 'x': | |
case 'X': | |
ishex = 1; | |
break; | |
case 'e': | |
case 'E': | |
if (!ishex || !isbinary) | |
isfloat = 1; | |
break; | |
case '.': | |
isfloat = 1; | |
break; | |
default: | |
break; | |
} | |
} | |
if (isfloat) { | |
return 0; /* Not supposed to have a float here */ | |
} else if (isbinary){ | |
char* strwo0b = strchr(sval, 'b'); | |
if(strwo0b == NULL) | |
strwo0b = strchr(sval, 'B'); | |
strwo0b = strwo0b+1; | |
long long int llval = strtoll(strwo0b,&endp,2); | |
long long int upperbits = llval >> 31; | |
/* will give -1 for negative, 0 or 1 for positive */ | |
if (valp && (upperbits == 0 || upperbits == -1 || upperbits == 1)) { | |
*valp = (unsigned) llval; | |
return 1; | |
} | |
return 0; | |
} else { | |
long long int llval = strtoll(sval, &endp, 0); | |
long long int upperbits = llval >> 31; | |
/* will give -1 for negative, 0 or 1 for positive */ | |
if (valp && (upperbits == 0 || upperbits == -1 || upperbits == 1)) { | |
*valp = (unsigned) llval; | |
return 1; | |
} | |
return 0; | |
} | |
} | |
const char *int_to_binary(int x) | |
{ | |
static char b[33]; | |
b[0] = '\0'; | |
int i; | |
for (i=0; i <32; i++) | |
{ | |
strcat(b,((x & (1<<(31-i))) != 0) ? "1" : "0"); | |
} | |
return b; | |
} | |
void show_int(unsigned uf) | |
{ | |
printf("Bin = 0b%s\t,Hex = 0x%.8x,\tSigned = %d,\tUnsigned = %u\n", | |
int_to_binary(uf),uf, (int) uf, uf); | |
} | |
void usage(char *fname) { | |
printf("Usage: %s val1 val2 ...\n", fname); | |
printf("Values may be given in hex or decimal\n"); | |
exit(0); | |
} | |
int main(int argc, char *argv[]) | |
{ | |
int i; | |
unsigned uf; | |
if (argc < 2) | |
usage(argv[0]); | |
for (i = 1; i < argc; i++) { | |
char *sval = argv[i]; | |
if (get_num_val(sval, &uf)) { | |
show_int(uf); | |
} else { | |
printf("Cannot convert '%s' to 32-bit number\n", sval); | |
} | |
} | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment