Can I use a binary literal in C or C++?
Asked Answered
R

24

245

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?

Rawlinson answered 10/4, 2010 at 0:35 Comment(9)
You know that 00010000 is octal, right? (And your declaration is missing a type.)Unlade
Here modern way using C++ literals.Hystero
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.Applaud
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.Hydrosol
@KeithThompson can you explain why that is octal?Bedraggled
@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.)Unlade
@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?Bedraggled
@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.Unlade
Possible duplicate of Binary literals?Nephoscope
M
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.

Montez answered 10/4, 2010 at 1:25 Comment(3)
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); }Nunley
@Roger thanks for the bitset tip, I already corrected the bit about setbase before I saw your comment though.Montez
Here's a tutorial on user-defined literals in c++11: 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.Wivinia
N
330

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;
Nightfall answered 10/4, 2010 at 6:57 Comment(8)
Several other compilers have this or other similar ways of expressing numbers in base 2.Deficient
Would be nice to have this standardized, but clang supports the same notation.Spinelli
It works in Clang, GCC, and TCC. It doesn't work in PCC. I doesn't have any other compiler to test with.Florettaflorette
I've seen a number of embedded-systems compilers that support it. I don't know any particular reason it shouldn't be a standard language feature.Peeples
@Spinelli open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3472.pdf (C++14.)Thighbone
For the record, this is not supported by MSVC2010, sadly.Thalia
This also works in the Arduino IDE, which makes sense given its typically embedded application.Boatbill
Also works perfectly for XC8 on PIC mcuMoa
R
151

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++).

Ruelu answered 7/4, 2015 at 8:38 Comment(3)
You can use ' to separate each part : "0b0000'0100'0100'0001Knuth
@Knuth Nice you can loose the first "Mellicent
This should be the accepted answer. Most of the other answers are sooo outdated.Balcer
I
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.

Immortalize answered 10/4, 2010 at 1:10 Comment(5)
Better version: bitbucket.org/kniht/scraps/src/tip/cpp/binary.hpp (binary<10>::value == binary<010>::value and some error checking)Nunley
Somehow missed this one before I posted my own nearly identical answer. But in mine the leading digit has to be 0, not 1.Nicely
A better version of this template idea: code.google.com/p/cpp-binary-constantsMobocracy
@ValentinGalea - why the google version better than this?Cassidycassie
This is freaking impressive. Too bad it doesn't work for high number of bits.Profuse
M
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.

Montez answered 10/4, 2010 at 1:25 Comment(3)
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); }Nunley
@Roger thanks for the bitset tip, I already corrected the bit about setbase before I saw your comment though.Montez
Here's a tutorial on user-defined literals in c++11: 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.Wivinia
C
35

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);
Catchall answered 28/9, 2011 at 1:51 Comment(2)
Why is e.g. B_0100 not used (instead of 0100)? As in e.g. char b = BYTE(0100,0001);.Hellas
@PeterMortensen The B_ gets added by the _B2H preprocessor function.Aphaeresis
P
22

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.)

Prefer answered 10/4, 2010 at 0:39 Comment(7)
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 , thanksRawlinson
The B8 macro works by converting the "binary" literal to a hex literal and extracting every 4th bit.Terminology
I wonder what 0x##n##LU means? Never encountered such syntax.Prefer
@hamza: it is indeed rather intricate. But what you need to understand is just from #include<stdio> onwards.Prefer
@Federico: The ## preprocessor operator pastes tokens together. So, in this case, if you call HEX__(10), it expands to 0x10LU.Platinize
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.Brandybrandyn
Oddly, this set of macros will produce some interesting results for: B16(ABCDEF89,01234567); Otherwise, very clever!Refulgent
P
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.

Penicillium answered 10/4, 2010 at 0:55 Comment(5)
So, how large a file would the CPP need to read if you had all the macros for a long long int?Immortalize
@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…Penicillium
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 ##.Sciential
@Sciential 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. =)Penicillium
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.)Penicillium
H
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
Haughty answered 7/11, 2013 at 17:50 Comment(0)
C
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).

Currant answered 10/4, 2010 at 0:40 Comment(0)
N
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.

Nicely answered 10/4, 2010 at 2:56 Comment(0)
L
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.

Landel answered 10/4, 2010 at 0:37 Comment(4)
can i at least show the Binary value of an hexadecimal in a print or a cout function ?Rawlinson
Yes you can <shameless_plug> stackoverflow.com/questions/2611764#2611883 </shameless_plug>Montez
Some C compilers support 0b100101 for binary literals, but it is a nonstandard extension, unfortunately.Americium
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!)Brandybrandyn
D
6

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.

Daph answered 17/7, 2014 at 22:9 Comment(1)
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'Tenenbaum
G
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;
}
Goldsworthy answered 28/6, 2012 at 21:34 Comment(0)
T
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].

Transmundane answered 10/4, 2010 at 0:44 Comment(0)
U
2

You can use a bitset

bitset<8> b(string("00010000"));
int i = (int)(bs.to_ulong());
cout<<i;
Unpaid answered 2/6, 2014 at 8:5 Comment(0)
D
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; */
Defense answered 17/10, 2016 at 1:19 Comment(0)
S
2

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

unsigned char a = 0b00110011;
Shier answered 5/8, 2021 at 19:39 Comment(0)
B
2

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.

Benedicite answered 30/1, 2023 at 20:39 Comment(0)
S
0

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.

Shipboard answered 4/3, 2015 at 14:17 Comment(0)
C
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;
}
Chance answered 19/7, 2021 at 18:48 Comment(3)
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, 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? for more information on how deleting content works on this site.Cheeky
Also, I fixed the code formatting for you, in case that was why you removed the content.Cheeky
This answer does not provide any new insight to the problem, and its usability is limited to at most 9-digit binary numbers.Gambrel
C
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.

Cynewulf answered 7/8, 2022 at 13:18 Comment(0)
H
-2

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

Heder answered 10/4, 2010 at 2:27 Comment(0)
C
-3

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;

}

Chance answered 19/7, 2021 at 18:58 Comment(1)
You have already posted this answer.Exequies
D
-11

You could try using an array of bool:

bool i[8] = {0,0,1,1,0,1,0,1}
Disembarrass answered 29/6, 2015 at 12:13 Comment(2)
Lots of downvotes, no explanation. Here is your explanation: https://mcmap.net/q/119010/-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.Bentonbentonite
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?Echikson

© 2022 - 2024 — McMap. All rights reserved.