summaryrefslogtreecommitdiff
path: root/num.c
blob: 8670f6187355245ba46937439637b1344c16608a (plain)
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>

static char *binary(unsigned long long i, int w)
{
    static char buff[1024];
    int first=1;
    char *p;
    unsigned long long b;
    int c;

    b = 1ull<<(w-1);

    p = buff;

    for(c = w; c--; b = b>>1ull)
    {
	if (((c+1)%4) == 0 && !first)
	{
	    *p++=' ';
	}

	if(i&b)
	{
	    *p++='1';
	}
	else
	{
	    *p++='0';
	}

	first=0;
    }

    *p = 0;

    return buff;
}


static char *ascii(unsigned long long num, int l)
{
    static char s[1024];
    int f;
    unsigned char c;

    s[l]=0;

    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;
}


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);

	if (num < 0x100ull)
	{
	    h_width = 2;
	    b_width = 8;
	    snum=(signed char)num;
	}
	else if (num < 0x10000ull)
	{
	    h_width = 4;
	    b_width = 16;
	    snum=(signed short)num;
	}
	else if (num < 0x100000000ull)
	{
	    h_width = 8;
	    b_width = 32;
	    snum=(signed long)num;
	}
	else
	{
	    h_width = 16;
	    b_width = 64;
	    snum=(signed long long)num;
	}

	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/8));
    }

    return EXIT_SUCCESS;
}