Search code examples
c++cbitoctal

Issue reading in a char array using sscanf in octal using either C or C++


When trying to read in the octal value for "24" to an unsigned int, I get 0. Simply passing in the decimal value as a char array works.

I need the final value as a 32 bit unsigned int. The initial value is read in from a binary file.

MCVE

simple.cpp

#include <iostream>
#include <cstdlib>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
    char count[4] = "\030\000\000"; // Just "24" works
    __uint32_t value;
    sscanf(count, "%x", &value);
    fprintf(stderr, "%x", value);
    return 0;
}

Compiled and executed using

$ g++ simple.cpp -g
$ ./a.out
0
$ g++ --version
g++ (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609

Solution

  • The octal value 030 is a single character representing the special "CAN" (Cancel) control character in ASCII encoding (which is the most common encoding for the English alphabet and digits and punctuation).

    When you use scanf (or its sibling sscanf) it will try to read digits, which in the ASCII encoding are the values 060 to 071 (for the digits 0 to 9, inclusive).

    To be able to use sscanf to read the number 24 you need to the two characters '2' and '4'. I.e. "24" (or "\062\064").


    If you want to convert the single character '\030' to the integer value 24, then just do e.g.

    value = count[0];