c++binaryhex

What does "0b" and "0x" stand for when assigning binary and hexadecimal?


When assigning a binary value and a hexadecimal value directly you can do it as follows (respectively):

uint8_t val1 = 0b10101;
uint8_t val2 = 0xFF;

What does the 0b and 0x mean? Specifically the 0 at the front. Can you have other values instead of 0?

Also as another curious question, what other characters can go in the place of b and x? Is there one for octal as an example?


Solution

  • Any and all integer literals you can create are summarized in the C++ standard by the grammar production at [lex.icon]

    integer-literal:
        binary-literal integer-suffixopt
        octal-literal integer-suffixopt
        decimal-literal integer-suffixopt
        hexadecimal-literal integer-suffixopt
    
    binary-literal:
        0b binary-digit
        0B binary-digit
        binary-literal 'opt binary-digit
    
    octal-literal:
        0
        octal-literal 'opt octal-digit
    
    decimal-literal:
        nonzero-digit
        decimal-literal 'opt digit
    
    hexadecimal-literal:
        hexadecimal-prefix hexadecimal-digit-sequence
    
    binary-digit:
        0
        1
    
    octal-digit: one of
        0  1  2  3  4  5  6  7
    
    nonzero-digit: one of
        1  2  3  4  5  6  7  8  9
    
    hexadecimal-prefix: one of
        0x  0X
    
    hexadecimal-digit-sequence:
        hexadecimal-digit
        hexadecimal-digit-sequence 'opt hexadecimal-digit
    
    hexadecimal-digit: one of
        0  1  2  3  4  5  6  7  8  9
        a  b  c  d  e  f
        A  B  C  D  E  F
    

    As we can deduce from the grammar, there are four types of integer literals:

    The leading 0 for octal numbers can be thought of as the "O" in "Octal". The other prefixes use a leading zero to mark the beginning of a number that should not be interpreted as decimal. "B" is intuitively for "binary", while "X" is for "hexadecimal".