From 7633ca67346c09dbd7b6670d55d8516cbae4e476 Mon Sep 17 00:00:00 2001 From: Ian C Date: Mon, 8 Nov 2010 11:00:19 +0000 Subject: Tidied up num.c and made it work with "long long" correctly. --- num.c | 187 ++++++++++++++++++++++++++++++++---------------------------------- 1 file changed, 91 insertions(+), 96 deletions(-) (limited to 'num.c') diff --git a/num.c b/num.c index b24da39..d826f8d 100644 --- a/num.c +++ b/num.c @@ -1,128 +1,123 @@ +#include #include +#include +#include -#define LONG 0 -#define WORD 1 -#define BYTE 2 - -main(argc,argv) -int argc; -char *argv[]; - -{ - signed long snum; - unsigned long num; - unsigned short word; - unsigned char byte; - double dbl; - int mode=LONG; - int arg=0; - int f; - char *binary(); - char *ascii(); - - if(argc==1) - { - printf("%s: usage %s N1 [..Nn]\n",argv[0],argv[0]); - exit(-1); - } - - for(f=1;f>1) + for(c = w; c--; b = b>>1) + { + if (((c+1)%4) == 0 && !first) { - if (!((c+1)%4)&&!first) *p++=' '; + } if(i&b) + { *p++='1'; + } else + { *p++='0'; + } first=0; - } + } - *p='\0'; + *p = 0; - return(buff); + return buff; } -char *ascii(num,l) -unsigned long num; +static char *ascii(unsigned long long num, int l) { - static char s[5]; + static char s[1024]; int f; unsigned char c; s[l]=0; - for(f=0;f=32)&&(c<127)) + for(f = 0; f < l; f++) + { + c = num&0xff; + + if (isprint(c)) + { s[(l-1)-f]=c; + } else + { s[(l-1)-f]='.'; - num=num>>8; } - return(s); + num = num>>8; + } + + return s; +} + + +int main(int argc, char *argv[]) +{ + long long snum; + long long num; + unsigned short word; + unsigned char byte; + int h_width; + int b_width; + int f; + + if(argc == 1) + { + printf("%s: usage %s N1 [..Nn]\n",argv[0],argv[0]); + exit(EXIT_FAILURE); + } + + for(f = 1; f < argc; f++) + { + num = strtoull(argv[f], NULL, 0); + snum=(signed long long)num; + + if (num < 0x100ull) + { + h_width = 2; + b_width = 8; + } + else if (num < 0x10000ull) + { + h_width = 4; + b_width = 16; + } + else if (num < 0x100000000ull) + { + h_width = 8; + b_width = 32; + } + else + { + h_width = 16; + b_width = 64; + } + + printf("Original : %s\n", argv[f]); + printf("Octal : %llo\n", num); + printf("Uns. Dec : %llu\n", num); + printf("Sgn. Dec : %lld\n", snum); + printf("Hex : %*.*llX\n", h_width, h_width, num); + printf("Binary : %s\n", binary(num, b_width)); + printf("Ascii : %s\n", ascii(num, b_width/4)); + } + + return EXIT_SUCCESS; } -- cgit v1.2.3