241

I need to work with a binary number.

I tried writing:

const char x = 00010000;

But it didn't work.

I know that I can use a hexadecimal number that has the same value as 00010000, but I want to know if there is a type in C++ for binary numbers, and if there isn't, is there another solution for my problem?

hamza
  • 2,714
  • 3
  • 19
  • 14
  • 61
    You know that `00010000` is octal, right? (And your declaration is missing a type.) – Keith Thompson Sep 28 '11 at 02:32
  • [Here](http://stackoverflow.com/questions/537303/binary-literals/538101#538101) modern way using C++ literals. – Lol4t0 May 14 '13 at 16:11
  • I would consider using hex. As you see below, it's just a more compressed form of binary, and you're far less likely to swap a 0 and 1. – Joel May 20 '13 at 21:15
  • 2
    C++14 added a feature for this. See my new answer for more details at the bottom. Of course, it does require a compiler that implements it. – László Papp Dec 24 '13 at 03:20
  • @KeithThompson can you explain why that is octal? – Aurelius Oct 16 '15 at 16:40
  • @FormlessCloud: Because it starts with `0`. An integer literal is hexadecimal if it starts with `0x` or `0X`, binary (in C++14 or later) if it starts with `0b` or `0B`, octal if it starts with `0`, and decimal otherwise. (Yes, that means `0` is octal.) – Keith Thompson Oct 16 '15 at 18:32
  • @KeithThompson mmm are these like conventions or something, to recognise univocally a number of a given base? Becase `x` is not hexadecimal (`A`, `B`, `C`, `D`, `E`, `F`), and writing zeros in front of binary or hexadecimal numbers doesn't affect either one of them, so is it arbitrary to choose `0b` for binaries? – Aurelius Oct 16 '15 at 21:30
  • 1
    @FormlessCloud: These are the syntax rules given in the C and C++ standards (`0b` appears only in C++14). They're designed to be unambiguous. – Keith Thompson Oct 16 '15 at 21:39
  • 3
    Possible duplicate of [Binary literals?](https://stackoverflow.com/questions/537303/binary-literals) – M.J. Rayburn Nov 09 '18 at 07:16

24 Answers24

326

If you are using GCC then you can use a GCC extension (which is included in the C++14 standard) for this:

int x = 0b00010000;
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
qrdl
  • 34,062
  • 14
  • 56
  • 86
146

You can use binary literals. They are standardized in C++14. For example,

int x = 0b11000;

Support in GCC

Support in GCC began in GCC 4.3 (see https://gcc.gnu.org/gcc-4.3/changes.html) as extensions to the C language family (see https://gcc.gnu.org/onlinedocs/gcc/C-Extensions.html#C-Extensions), but since GCC 4.9 it is now recognized as either a C++14 feature or an extension (see Difference between GCC binary literals and C++14 ones?)

Support in Visual Studio

Support in Visual Studio started in Visual Studio 2015 Preview (see https://www.visualstudio.com/news/vs2015-preview-vs#C++).

Community
  • 1
  • 1
Mohamed El-Nakeep
  • 6,580
  • 4
  • 35
  • 39
76
template<unsigned long N>
struct bin {
    enum { value = (N%10)+2*bin<N/10>::value };
} ;

template<>
struct bin<0> {
    enum { value = 0 };
} ;

// ...
    std::cout << bin<1000>::value << '\n';

The leftmost digit of the literal still has to be 1, but nonetheless.

wilhelmtell
  • 57,473
  • 20
  • 96
  • 131
72

You can use BOOST_BINARY while waiting for C++0x. :) BOOST_BINARY arguably has an advantage over template implementation insofar as it can be used in C programs as well (it is 100% preprocessor-driven.)

To do the converse (i.e. print out a number in binary form), you can use the non-portable itoa function, or implement your own.

Unfortunately you cannot do base 2 formatting with STL streams (since setbase will only honour bases 8, 10 and 16), but you can use either a std::string version of itoa, or (the more concise, yet marginally less efficient) std::bitset.

#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;
}

produces:

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

Also read Herb Sutter's The String Formatters of Manor Farm for an interesting discussion.

S.S. Anne
  • 15,171
  • 8
  • 38
  • 76
vladr
  • 65,483
  • 18
  • 129
  • 130
  • 2
    As the very page to which you link says, you may only use 8, 10, or 16 with setbase. However: `int main() { cout << bitset<8>(42); }` –  Apr 10 '10 at 02:40
  • @Roger thanks for the `bitset` tip, I already corrected the bit about `setbase` before I saw your comment though. – vladr Apr 10 '10 at 02:50
  • Here's a tutorial on user-defined literals in c++11: http://akrzemi1.wordpress.com/2012/10/23/user-defined-literals-part-ii/. Evidently c++1y (a.k.a. c++14) will include binary literals in the standard. – cheshirekow Sep 14 '13 at 21:06
34

A few compilers (usually the ones for microcontrollers) has a special feature implemented within recognizing literal binary numbers by prefix "0b..." preceding the number, although most compilers (C/C++ standards) don't have such feature and if it is the case, here it is my alternative solution:

#define B_0000    0
#define B_0001    1
#define B_0010    2
#define B_0011    3
#define B_0100    4
#define B_0101    5
#define B_0110    6
#define B_0111    7
#define B_1000    8
#define B_1001    9
#define B_1010    a
#define B_1011    b
#define B_1100    c
#define B_1101    d
#define B_1110    e
#define B_1111    f

#define _B2H(bits)    B_##bits
#define B2H(bits)    _B2H(bits)
#define _HEX(n)        0x##n
#define HEX(n)        _HEX(n)
#define _CCAT(a,b)    a##b
#define CCAT(a,b)   _CCAT(a,b)

#define BYTE(a,b)        HEX( CCAT(B2H(a),B2H(b)) )
#define WORD(a,b,c,d)    HEX( CCAT(CCAT(B2H(a),B2H(b)),CCAT(B2H(c),B2H(d))) )
#define DWORD(a,b,c,d,e,f,g,h)    HEX( CCAT(CCAT(CCAT(B2H(a),B2H(b)),CCAT(B2H(c),B2H(d))),CCAT(CCAT(B2H(e),B2H(f)),CCAT(B2H(g),B2H(h)))) )

// Using example
char b = BYTE(0100,0001); // Equivalent to b = 65; or b = 'A'; or b = 0x41;
unsigned int w = WORD(1101,1111,0100,0011); // Equivalent to w = 57155; or w = 0xdf43;
unsigned long int dw = DWORD(1101,1111,0100,0011,1111,1101,0010,1000); //Equivalent to dw = 3745774888; or dw = 0xdf43fd28;

Disadvantages (it's not such a big ones):

  • The binary numbers have to be grouped 4 by 4;
  • The binary literals have to be only unsigned integer numbers;

Advantages:

  • Total preprocessor driven, not spending processor time in pointless operations (like "?.. :..", "<<", "+") to the executable program (it may be performed hundred of times in the final application);
  • It works "mainly in C" compilers and C++ as well (template+enum solution works only in C++ compilers);
  • It has only the limitation of "longness" for expressing "literal constant" values. There would have been earlyish longness limitation (usually 8 bits: 0-255) if one had expressed constant values by parsing resolve of "enum solution" (usually 255 = reach enum definition limit), differently, "literal constant" limitations, in the compiler allows greater numbers;
  • Some other solutions demand exaggerated number of constant definitions (too many defines in my opinion) including long or several header files (in most cases not easily readable and understandable, and make the project become unnecessarily confused and extended, like that using "BOOST_BINARY()");
  • Simplicity of the solution: easily readable, understandable and adjustable for other cases (could be extended for grouping 8 by 8 too);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
21

This thread may help.

/* Helper macros */
#define HEX__(n) 0x##n##LU
#define B8__(x) ((x&0x0000000FLU)?1:0) \
+((x&0x000000F0LU)?2:0) \
+((x&0x00000F00LU)?4:0) \
+((x&0x0000F000LU)?8:0) \
+((x&0x000F0000LU)?16:0) \
+((x&0x00F00000LU)?32:0) \
+((x&0x0F000000LU)?64:0) \
+((x&0xF0000000LU)?128:0)

/* User macros */
#define B8(d) ((unsigned char)B8__(HEX__(d)))
#define B16(dmsb,dlsb) (((unsigned short)B8(dmsb)<<8) \
+ B8(dlsb))
#define B32(dmsb,db2,db3,dlsb) (((unsigned long)B8(dmsb)<<24) \
+ ((unsigned long)B8(db2)<<16) \
+ ((unsigned long)B8(db3)<<8) \
+ B8(dlsb))


#include <stdio.h>

int main(void)
{
    // 261, evaluated at compile-time
    unsigned const number = B16(00000001,00000101);

    printf("%d \n", number);
    return 0;
}

It works! (All the credits go to Tom Torfs.)

Federico A. Ramponi
  • 46,145
  • 29
  • 109
  • 133
  • i did not really understand ( i m a beginner in programming & specially in C++) but it seems interesting so i will try to understand it after some more C++ studies , thanks – hamza Apr 10 '10 at 00:57
  • 3
    The B8 macro works by converting the "binary" literal to a hex literal and extracting every 4th bit. – dan04 Apr 10 '10 at 01:04
  • I wonder what 0x##n##LU means? Never encountered such syntax. – Federico A. Ramponi Apr 10 '10 at 01:07
  • @hamza: it is indeed rather intricate. But what you need to understand is just from #include onwards. – Federico A. Ramponi Apr 10 '10 at 01:10
  • 8
    @Federico: The `##` preprocessor operator pastes tokens together. So, in this case, if you call `HEX__(10)`, it expands to `0x10LU`. – James McNellis Apr 10 '10 at 01:13
  • Very clever. You don't even need to worry about the literal being interpreted as octal since it simply gets concatenated directly to the `0x`. Leading zeros are completely optional. – mbauman Apr 10 '10 at 03:32
  • Oddly, this set of macros will produce some interesting results for: `B16(ABCDEF89,01234567);` Otherwise, very clever! – abelenky Jun 28 '12 at 22:04
20

As already answered, the C standards have no way to directly write binary numbers. There are compiler extensions, however, and apparently C++14 includes the 0b prefix for binary. (Note that this answer was originally posted in 2010.)

One popular workaround is to include a header file with helper macros. One easy option is also to generate a file that includes macro definitions for all 8-bit patterns, e.g.:

#define B00000000 0
#define B00000001 1
#define B00000010 2
…

This results in only 256 #defines, and if larger than 8-bit binary constants are needed, these definitions can be combined with shifts and ORs, possibly with helper macros (e.g., BIN16(B00000001,B00001010)). (Having individual macros for every 16-bit, let alone 32-bit, value is not plausible.)

Of course the downside is that this syntax requires writing all the leading zeroes, but this may also make it clearer for uses like setting bit flags and contents of hardware registers. For a function-like macro resulting in a syntax without this property, see bithacks.h linked above.

S.S. Anne
  • 15,171
  • 8
  • 38
  • 76
Arkku
  • 41,011
  • 10
  • 62
  • 84
  • 2
    So, how large a file would the CPP need to read if you had all the macros for a `long long int`? – wilhelmtell Apr 10 '10 at 02:03
  • 3
    @wilhelmtell: And what is the relevance of that when I specified “all *8-bit* patterns” (= 256 lines), and suggested combining larger quantities from those? Even the BOOST_BINARY of the accepted answer defines all 8-bit patterns in the header… – Arkku Apr 10 '10 at 14:12
  • Not sure if upvote or downvote. On the one hand it is smart, because a simple text replacement is done before compilation. And you can simple write a generator to create such a header file also for data types larger than 8-Bit. On the other hand, I do neither know how many #define a pre-processor can handle, nor if they can be handled efficiently. Maybe it is possible to reduce the amount of necessary definitions by using helper macros for concatenation with `##`. – tangoal Mar 09 '21 at 12:02
  • @tangoal As I say in the answer, I suggest this only for 8-bit macros, and I explicitly state that I don't think 16-bit or higher are plausible to do, and I do also suggest combining higher widths (than 8 bits) with helper macros. So, if you downvote I would hope the reason is not the same old "didn't read the answer but this doesn't work for more than 8 bits" because it's not intended to. =) – Arkku Mar 09 '21 at 13:37
  • As for the concatenation with `##`, I think that would require a syntax like `BIN16(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1)` which I don't think is much of an improvement over the `BIN16(B00000001,B00001010)` suggested in the answer. Or did you have some other idea than one of these basic forms? (Admittedly an editor with smart autocompletion might help with the former syntax and put the exact right amount of arguments with placeholders, which could be seen as an improvement even though it is not so nice to type by hand when you have to count to 16.) – Arkku Mar 09 '21 at 13:42
19

The C++ over-engineering mindset is already well accounted for in the other answers here. Here's my attempt at doing it with a C, keep-it-simple-ffs mindset:

unsigned char x = 0xF; // binary: 00001111
Craig
  • 207
  • 2
  • 2
13

C does not have native notation for pure binary numbers. Your best bet here would be either octal (e.g. 07777) of hexadecimal (e.g. 0xfff).

Nikolai Fetissov
  • 82,306
  • 11
  • 110
  • 171
11

You can use the function found in this question to get up to 22 bits in C++. Here's the code from the link, suitably edited:

template< unsigned long long N >
struct binary
{
  enum { value = (N % 8) + 2 * binary< N / 8 > :: value } ;
};

template<>
struct binary< 0 >
{
  enum { value = 0 } ;
};

So you can do something like binary<0101011011>::value.

Community
  • 1
  • 1
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
7

The smallest unit you can work with is a byte (which is of char type). You can work with bits though by using bitwise operators.

As for integer literals, you can only work with decimal (base 10), octal (base 8) or hexadecimal (base 16) numbers. There are no binary (base 2) literals in C nor C++.

Octal numbers are prefixed with 0 and hexadecimal numbers are prefixed with 0x. Decimal numbers have no prefix.

In C++0x you'll be able to do what you want by the way via user defined literals.

Brian R. Bondy
  • 339,232
  • 124
  • 596
  • 636
  • can i at least show the Binary value of an hexadecimal in a print or a cout function ? – hamza Apr 10 '10 at 01:48
  • Yes you can `` http://stackoverflow.com/questions/2611764#2611883 `` – vladr Apr 10 '10 at 02:05
  • 5
    Some C compilers support 0b100101 for binary literals, but it is a nonstandard extension, unfortunately. – Joey Adams Apr 10 '10 at 03:10
  • 3
    Note that, while it's not defined in the standard, some compilers (notably ones for microcontrollers and embedded systems) add the syntax for binary in the form `0b00101010` as a convenience. SDCC is one, and I'm sure there are others that do, too. (Edit: Hah, beat me to it, @Joey!) – mbauman Apr 10 '10 at 03:13
5

Based on some other answers, but this one will reject programs with illegal binary literals. Leading zeroes are optional.

template<bool> struct BinaryLiteralDigit;

template<> struct BinaryLiteralDigit<true> {
    static bool const value = true;
};

template<unsigned long long int OCT, unsigned long long int HEX>
struct BinaryLiteral {
    enum {
        value = (BinaryLiteralDigit<(OCT%8 < 2)>::value && BinaryLiteralDigit<(HEX >= 0)>::value
            ? (OCT%8) + (BinaryLiteral<OCT/8, 0>::value << 1)
            : -1)
    };
};

template<>
struct BinaryLiteral<0, 0> {
    enum {
        value = 0
    };
};

#define BINARY_LITERAL(n) BinaryLiteral<0##n##LU, 0x##n##LU>::value

Example:

#define B BINARY_LITERAL

#define COMPILE_ERRORS 0

int main (int argc, char ** argv) {
    int _0s[] = { 0, B(0), B(00), B(000) };
    int _1s[] = { 1, B(1), B(01), B(001) };
    int _2s[] = { 2, B(10), B(010), B(0010) };
    int _3s[] = { 3, B(11), B(011), B(0011) };
    int _4s[] = { 4, B(100), B(0100), B(00100) };

    int neg8s[] = { -8, -B(1000) };

#if COMPILE_ERRORS
    int errors[] = { B(-1), B(2), B(9), B(1234567) };
#endif

    return 0;
}
Thomas Eding
  • 35,312
  • 13
  • 75
  • 106
5

You can also use inline assembly like this:

int i;

__asm {
    mov eax, 00000000000000000000000000000000b
    mov i,   eax
}

std::cout << i;

Okay, it might be somewhat overkill, but it works.

S.S. Anne
  • 15,171
  • 8
  • 38
  • 76
renger
  • 775
  • 1
  • 7
  • 11
  • 4
    Your solution is not multi-platform. In many architectures you cannot include assembly code in C. Specifically in Microsoft Visual studio compiler you can (when compiled for x86 32bits). But how do you even know if your processor has 'eax' register? Think of ARM processors in mobile phones, x64 processor, etc. They don't have 'eax'. MIPS processor does not even have command 'mov' – DanielHsH Sep 21 '15 at 17:51
3

The "type" of a binary number is the same as any decimal, hex or octal number: int (or even char, short, long long).

When you assign a constant, you can't assign it with 11011011 (curiously and unfortunately), but you can use hex. Hex is a little easier to mentally translate. Chunk in nibbles (4 bits) and translate to a character in [0-9a-f].

Stephen
  • 47,994
  • 7
  • 61
  • 70
3

From C++14 you can use Binary Literals, now they are part of the language:

unsigned char a = 0b00110011;
Konstantin Burlachenko
  • 5,233
  • 2
  • 41
  • 40
2

You can use a bitset

bitset<8> b(string("00010000"));
int i = (int)(bs.to_ulong());
cout<<i;
Deqing
  • 14,098
  • 15
  • 84
  • 131
2

I extended the good answer given by @renato-chandelier by ensuring the support of:

  • _NIBBLE_(…) – 4 bits, 1 nibble as argument
  • _BYTE_(…) – 8 bits, 2 nibbles as arguments
  • _SLAB_(…) – 12 bits, 3 nibbles as arguments
  • _WORD_(…) – 16 bits, 4 nibbles as arguments
  • _QUINTIBBLE_(…) – 20 bits, 5 nibbles as arguments
  • _DSLAB_(…) – 24 bits, 6 nibbles as arguments
  • _SEPTIBBLE_(…) – 28 bits, 7 nibbles as arguments
  • _DWORD_(…) – 32 bits, 8 nibbles as arguments

I am actually not so sure about the terms “quintibble” and “septibble”. If anyone knows any alternative please let me know.

Here is the macro rewritten:

#define __CAT__(A, B) A##B
#define _CAT_(A, B) __CAT__(A, B)

#define __HEX_0000 0
#define __HEX_0001 1
#define __HEX_0010 2
#define __HEX_0011 3
#define __HEX_0100 4
#define __HEX_0101 5
#define __HEX_0110 6
#define __HEX_0111 7
#define __HEX_1000 8
#define __HEX_1001 9
#define __HEX_1010 a
#define __HEX_1011 b
#define __HEX_1100 c
#define __HEX_1101 d
#define __HEX_1110 e
#define __HEX_1111 f

#define _NIBBLE_(N1) _CAT_(0x, _CAT_(__HEX_, N1))
#define _BYTE_(N1, N2) _CAT_(_NIBBLE_(N1), _CAT_(__HEX_, N2))
#define _SLAB_(N1, N2, N3) _CAT_(_BYTE_(N1, N2), _CAT_(__HEX_, N3))
#define _WORD_(N1, N2, N3, N4) _CAT_(_SLAB_(N1, N2, N3), _CAT_(__HEX_, N4))
#define _QUINTIBBLE_(N1, N2, N3, N4, N5) _CAT_(_WORD_(N1, N2, N3, N4), _CAT_(__HEX_, N5))
#define _DSLAB_(N1, N2, N3, N4, N5, N6) _CAT_(_QUINTIBBLE_(N1, N2, N3, N4, N5), _CAT_(__HEX_, N6))
#define _SEPTIBBLE_(N1, N2, N3, N4, N5, N6, N7) _CAT_(_DSLAB_(N1, N2, N3, N4, N5, N6), _CAT_(__HEX_, N7))
#define _DWORD_(N1, N2, N3, N4, N5, N6, N7, N8) _CAT_(_SEPTIBBLE_(N1, N2, N3, N4, N5, N6, N7), _CAT_(__HEX_, N8))

And here is Renato's using example:

char b = _BYTE_(0100, 0001); /* equivalent to b = 65; or b = 'A'; or b = 0x41; */
unsigned int w = _WORD_(1101, 1111, 0100, 0011); /* equivalent to w = 57155; or w = 0xdf43; */
unsigned long int dw = _DWORD_(1101, 1111, 0100, 0011, 1111, 1101, 0010, 1000); /* Equivalent to dw = 3745774888; or dw = 0xdf43fd28; */
madmurphy
  • 1,451
  • 11
  • 20
1

Just use the standard library in C++:

#include <bitset>

You need a variable of type std::bitset:

std::bitset<8ul> x;
x = std::bitset<8>(10);
for (int i = x.size() - 1; i >= 0; i--) {
      std::cout << x[i];
}

In this example, I stored the binary form of 10 in x.

8ul defines the size of your bits, so 7ul means seven bits and so on.

S.S. Anne
  • 15,171
  • 8
  • 38
  • 76
Hadi Rasekh
  • 2,622
  • 2
  • 20
  • 28
0

Here is my function without adding Boost library :

usage : BOOST_BINARY(00010001);

int BOOST_BINARY(int a){
    int b = 0;
    
    for (int i = 0;i < 8;i++){
        b += a % 10 << i;
        a = a / 10;
    }
    
    return b;
}
Ryan M
  • 18,333
  • 31
  • 67
  • 74
bthxyz
  • 1
  • 1
  • 1
    Please don't make more work for others by vandalizing your posts. By posting on the Stack Exchange (SE) network, you've granted a non-revocable right, under the [CC BY-SA license](https://creativecommons.org/licenses/by-sa/4.0), for SE to distribute the content (regardless of your future choices). By SE policy, the non-vandalized version is distributed. Thus, any such destructive edits will be reverted. Please see [How does deleting work?](https://meta.stackexchange.com/q/5221) for more information on how deleting content works on this site. – Ryan M Jul 19 '21 at 18:55
  • Also, I fixed the code formatting for you, in case that was why you removed the content. – Ryan M Jul 19 '21 at 18:56
  • This answer does not provide any new insight to the problem, and its usability is limited to at most 9-digit binary numbers. – zkoza Jul 19 '21 at 23:32
0

I nominate my solution:

    #define B(x)                \
       ((((x) >>  0) & 0x01)    \
      | (((x) >>  2) & 0x02)    \
      | (((x) >>  4) & 0x04)    \
      | (((x) >>  6) & 0x08)    \
      | (((x) >>  8) & 0x10)    \
      | (((x) >> 10) & 0x20)    \
      | (((x) >> 12) & 0x40)    \
      | (((x) >> 14) & 0x80))

const uint8 font6[] = {
    B(00001110),    //[00]
    B(00010001),
    B(00000001),
    B(00000010),
    B(00000100),
    B(00000000),
    B(00000100),
    B(00000000),

I define 8-bit fonts and graphics this way, but could work with wider fonts as well. The macro B can be defined to produce the 0b format, if supported by the compiler. Operation: the binary numbers are interpreted in octal, and then the bits are masked and shifted together. The intermediate value is limited by the largest integer the compiler can work with, I guess 64 bits should be OK.

It's entirely processed by the compiler, no code needed runtime.

vjalle
  • 549
  • 4
  • 13
0

Binary constants are to be standardised in C23. As of writing, 6.4.4.1/4 of the latest C2x draft standard says of the proposed notation:

[...] A binary constant consists of the prefix 0b or 0B followed by a sequence of the digits 0 or 1.

Brad Jones
  • 815
  • 7
  • 10
-1

C++ provides a standard template named std::bitset. Try it if you like.

S.S. Anne
  • 15,171
  • 8
  • 38
  • 76
Summer_More_More_Tea
  • 12,740
  • 12
  • 51
  • 83
-2

usage : BINARY(00010001);

int BINARY(int a){ int b = 0;

for (int i = 0;i < 8;i++){
    b += a % 10 << i;
    a = a / 10;
}

return b;

}

bthxyz
  • 1
  • 1
-10

You could try using an array of bool:

bool i[8] = {0,0,1,1,0,1,0,1}
S.S. Anne
  • 15,171
  • 8
  • 38
  • 76
  • 3
    Lots of downvotes, no explanation. Here is your explanation: https://stackoverflow.com/questions/2064550/c-why-bool-is-8-bits-long Also, each element in an array is at a different memory address. But we want a sequence of packed 1's and 0's at one address. – KANJICODER Nov 13 '19 at 17:10
  • One other thing about this is that it is a really big memory usage for the case. I suggest writing a function to represent binary digits better for the ease of the operations maybe? – Daniel Kaczmarczyk Jan 27 '21 at 04:55