Re: String to Octal
- From: Martin Ambuhl <mambuhl@xxxxxxxxxxxxx>
- Date: Tue, 21 Feb 2006 05:26:27 GMT
fuch6921@xxxxxxxxxxxxx wrote:
I want to read in an Octal number argument and have it stored as an
octal number. For instance the user will type: ./a.out 777 and it
will store the octal number 777. But it atoi does this as an interger,
and sscanf gives me 0.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char *src[] = { "309", "511", "777", "1ff", "1411" }, *endp;
size_t i, n = sizeof src / sizeof *src;
unsigned long x;
printf(" Note: when * endp = '\\0', it is printed as '$'\n\n");
for (i = 0; i < n; i++) {
printf(" The input string is \"%s\"\n", src[i]);
x = strtoul(src[i], &endp, 8);
printf("read as octal, *endp='%c',\n"
" value: %#lo (oct), %lu (dec), %#lx (hex)\n",
*endp ? *endp : '$', x, x, x);
x = strtoul(src[i], &endp, 10);
printf("read as decimal, *endp='%c',\n"
" value: %#lo (oct), %lu (dec), %#lx (hex)\n",
*endp ? *endp : '$', x, x, x);
x = strtoul(src[i], &endp, 16);
printf("read as hex, *endp='%c',\n"
" value: %#lo (oct), %lu (dec), %#lx (hex)\n\n",
*endp ? *endp : '$', x, x, x);
}
return 0;
}
Note: when * endp = '\0', it is printed as '$'
The input string is "309"
read as octal, *endp='9',
value: 030 (oct), 24 (dec), 0x18 (hex)
read as decimal, *endp='$',
value: 0465 (oct), 309 (dec), 0x135 (hex)
read as hex, *endp='$',
value: 01411 (oct), 777 (dec), 0x309 (hex)
The input string is "511"
read as octal, *endp='$',
value: 0511 (oct), 329 (dec), 0x149 (hex)
read as decimal, *endp='$',
value: 0777 (oct), 511 (dec), 0x1ff (hex)
read as hex, *endp='$',
value: 02421 (oct), 1297 (dec), 0x511 (hex)
The input string is "777"
read as octal, *endp='$',
value: 0777 (oct), 511 (dec), 0x1ff (hex)
read as decimal, *endp='$',
value: 01411 (oct), 777 (dec), 0x309 (hex)
read as hex, *endp='$',
value: 03567 (oct), 1911 (dec), 0x777 (hex)
The input string is "1ff"
read as octal, *endp='f',
value: 01 (oct), 1 (dec), 0x1 (hex)
read as decimal, *endp='f',
value: 01 (oct), 1 (dec), 0x1 (hex)
read as hex, *endp='$',
value: 0777 (oct), 511 (dec), 0x1ff (hex)
The input string is "1411"
read as octal, *endp='$',
value: 01411 (oct), 777 (dec), 0x309 (hex)
read as decimal, *endp='$',
value: 02603 (oct), 1411 (dec), 0x583 (hex)
read as hex, *endp='$',
value: 012021 (oct), 5137 (dec), 0x1411 (hex)
.
- Follow-Ups:
- Re: String to Octal
- From: suresh
- Re: String to Octal
- References:
- String to Octal
- From: fuch6921
- String to Octal
- Prev by Date: What is the advantage of malloc over calloc
- Next by Date: Re: how to print it out
- Previous by thread: Re: String to Octal
- Next by thread: Re: String to Octal
- Index(es):
Relevant Pages
|