Accept numbers written in decimal, hexadecimal (0x…) or octal (0…) and print each in decimal and hex.
Run as:./app 255 0x1F 0755
Solution
main.c
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
for (int i = 1; i < argc; i++) {
char *end;
long v = strtol(argv[i], &end, 0); /* base 0: the prefix decides */
if (end == argv[i] || *end != '\0') {
printf("%s -> invalid\n", argv[i]);
continue;
}
printf("%s -> dec %ld, hex 0x%lX\n", argv[i], v, (unsigned long) v);
}
return 0;
}
Output Verified by compiling and running
255 -> dec 255, hex 0xFF
0x1F -> dec 31, hex 0x1F
0755 -> dec 493, hex 0x1ED
With base 0, strtol() reads "0x" as hexadecimal and a leading 0 as octal – so 0755 (Unix file permissions) is 493. That leading-zero rule surprises users, so tools often require an explicit base.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!