Work with integers as binary in C++

Sometimes we need to work with integers in binary format and manipulate individual bytes in their binary representation. Here I will show two ways we can work with integers this way.

First way is to use ordinary int type.

First let’s create two variable in binary format:

Here we use use binary literals with ‘b’ character. These binary literals were standardized in C++14.

We can add two values like that

Result is 0x01001 or 9

If we print value with cout we will get decimal representation

To print the result in binary foramt we need to use bitset library. Import it

and print the variable

Here first non-type template parameter specifies the number of bits to store. 6 in our case.

Second way is to use byte type available since C++17. Notice according to documentation that it is not a character type and is not an arithmetic type. A byte is only a collection of bits, and onliy bitwise operators defined for it. Thus arithmetic ones can’t be used for it.

Include header file

Create byte object using regular int

Apply 2-bit left shift

and print result as int:

We can initialize variable using binary literal

Apply bitwise OR and AND operations

and print result as int:

That’s all you need to work with binary numbers in C++.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store