LearnFrenzy
Sign in Take a free test

Command Line Arguments · Command Line Programs · Question 7

Convert decimal, hex and octal arguments with strtol(…, 0) Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

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.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links