How do I enter binary numbers?

Asked 2 years ago, Updated 2 years ago, 56 views

const x = 00010000;

Like the octal and hexadecimal numbers start with 0x, Is there a function to specify binary numbers?

c c++ binary

2022-09-22 14:05

1 Answers

If you are using GCC, add 0b in front of the C++14 standard.

int x = 0b00010000;

To write the boost library, you must write the itoa() function. Because itoa() is a non-standard function, you may need to define it directly.

#include <boost/utility/binary.hpp>
#include <stdio.h>
#include <stdlib.h>
#include <bitset>
#include <iostream>
#include <iomanip>

using namespace std;

int main() {
  unsigned short b = BOOST_BINARY( 10010 );
  char buf[sizeof(b)*8+1];
  printf("hex: %04x, dec: %u, oct: %06o, bin: %16s\n", b, b, b, itoa(b, buf, 2));
  cout << setfill('0') <<
    "hex: " << hex << setw(4) << b << ", " <<
    "dec: " << dec << b << ", " <<
    "oct: " << oct << setw(6) << b << ", " <<
    "bin: " << bitset< 16 >(b) << endl;
  return 0;
}

Output:

hex: 0012, dec: 18, oct: 000022, bin:            10010
hex: 0012, dec: 18, oct: 000022, bin: 0000000000010010


2022-09-22 14:05

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.