Binary Literals? - C++ - Stack Overflow

Có thể bạn quan tâm

Just browsing Stack Overflow? Help us improve your experience. Sign up for research
    1. Home
    2. Questions
    3. Tags
    4. Users
    5. Companies
    6. Labs
    7. Jobs
    8. Discussions
    9. Collectives
    10. Communities for your favorite technologies. Explore all Collectives

  1. Teams

    Ask questions, find answers and collaborate at work with Stack Overflow for Teams.

    Try Teams for free Explore Teams
  2. Teams
  3. Ask questions, find answers and collaborate at work with Stack Overflow for Teams. Explore Teams

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

Get early access and see previews of new features.

Learn more about Labs Binary literals? Ask Question Asked 15 years, 9 months ago Modified 2 years, 7 months ago Viewed 106k times 74

In code, I sometimes see people specify constants in hex format like this:

const int has_nukes = 0x0001; const int has_bio_weapons = 0x0002; const int has_chem_weapons = 0x0004; // ... int arsenal = has_nukes | has_bio_weapons | has_chem_weapons; // all of them if(arsenal &= has_bio_weapons){ std::cout << "BIO!!" }

But it doesn't make sense to me to use the hex format here. Is there a way to do it directly in binary? Something like this:

const int has_nukes = 0b00000000000000000000000000000001; const int has_bio_weapons = 0b00000000000000000000000000000010; const int has_chem_weapons = 0b00000000000000000000000000000100; // ...

I know the C/C++ compilers won't compile this, but there must be a workaround? Is it possible in other languages like Java?

Share Improve this question Follow edited Sep 6, 2011 at 10:38 Joachim Sauer's user avatar Joachim Sauer 308k59 gold badges565 silver badges620 bronze badges asked Feb 11, 2009 at 15:23 Frank's user avatar FrankFrank 66k96 gold badges241 silver badges327 bronze badges 11
  • 3 I'm curious why the hex notation doesn't work for you? A number is a number. Binary notation would be much more prone to typos and would get really old for large numbers. – EBGreen Commented Feb 11, 2009 at 15:28
  • 31 Binary works better because the whole trick with the 'and' and 'or' operators works on the binary format and I want to be able to see the bit patterns. It's directly visible what bits are set. Even a beginner will be able to read the code without having to resort to a calculator. – Frank Commented Feb 11, 2009 at 15:31
  • 13 @EBGreen: when you're programming microcontrollers, using binary notation is Extremely useful. So much so that some uC C compilers actually accept numbers in the form of 0b00101010. – Rocketmagnet Commented Feb 11, 2009 at 15:33
  • 1 Well if this is micro controller code then sure. I don't think it is though. – EBGreen Commented Feb 11, 2009 at 15:36
  • 20 Careful with "arsenal &= has_bio_weapons". I think you meant "(arsenal & has_bio_weapons) == has_bio_weapons". – Mr Fooz Commented Feb 12, 2009 at 4:52
| Show 6 more comments

19 Answers 19

Sorted by: Reset to default Highest score (default) Trending (recent votes count more) Date modified (newest first) Date created (oldest first) 127

In C++14 you will be able to use binary literals with the following syntax:

0b010101010 /* more zeros and ones */

This feature is already implemented in the latest clang and gcc. You can try it if you run those compilers with -std=c++1y option.

Share Improve this answer Follow answered Sep 9, 2013 at 14:34 sasha.sochka's user avatar sasha.sochkasasha.sochka 14.7k10 gold badges45 silver badges68 bronze badges 8
  • It now works with clang-3.4 (See llvm.org/svn/llvm-project/cfe/trunk@194194); Just compiled and it indeed returns 3 : int main(int argc, char** argv) { int a = 0b00000011; return a; } – daminetreg Commented Nov 7, 2013 at 22:32
  • @daminetreg, yeah, it does. Actually I was talking exactly about clang 4.8 trunk in the post but didn't mention the version. – sasha.sochka Commented Nov 8, 2013 at 12:32
  • Isn't 4.8 the version of gcc ? Or did I miss something ? – daminetreg Commented Nov 8, 2013 at 23:50
  • Oops, my mistake, I was thinking about gcc while writing about clang. Of course, you're right. – sasha.sochka Commented Nov 9, 2013 at 14:24
  • WRT GCC and Clang, both support this syntax as an extension for both C and C++ and have long before C++1y was even proposed (Since GCC 4.3.) – Jonathan Baldwin Commented Jan 17, 2014 at 11:18
| Show 3 more comments 75

I'd use a bit shift operator:

const int has_nukes = 1<<0; const int has_bio_weapons = 1<<1; const int has_chem_weapons = 1<<2; // ... int dangerous_mask = has_nukes | has_bio_weapons | has_chem_weapons; bool is_dangerous = (country->flags & dangerous_mask) == dangerous_mask;

It is even better than flood of 0's.

Share Improve this answer Follow edited Feb 11, 2009 at 19:26 strager's user avatar strager 89.9k27 gold badges138 silver badges178 bronze badges answered Feb 11, 2009 at 15:32 Tometzky's user avatar TometzkyTometzky 23.8k5 gold badges63 silver badges78 bronze badges 5
  • 4 My wild guess is that old compilers were dumb enough to actually shifted the 1 around, instead of converting that expression to an integer literal. – Calyth Commented Feb 11, 2009 at 18:40
  • I would suggest using an enum instead of constants. However, there is the problem where you cannot OR enums. You could make a class which overrides these, but you'll lose compile-time performance! Ah, such is life. – strager Commented Feb 11, 2009 at 19:26
  • 3 One thing to watch out for when using this syntax, is that if you ever change the type to a wider integral type (e.g. unsigned long long), you'll have to change all the 1<<N to 1ULL<<N, at least for large N, otherwise silent unpredictable behavior could occur (if you're lucky you'll get a compiler warning)! (This is vs. the hex syntax where you wouldn't need to add a special suffix, since a sufficiently large integral type will be selected by the compiler.) – ndkrempel Commented May 19, 2012 at 23:24
  • 1 @strager what benefit did enums have, other than being inlinable by less efficient compilers? anyway since C++11 added constexpr, that's always preferable. plain old consts could be inlined as literals too, though constexpr signals intent better and opens up a lot of other possibilities. – underscore_d Commented Apr 20, 2016 at 20:00
  • 1 Note that the is_dangerous value will only be true if all bitmasks are set. If you want to logically OR the conditions, you would check if the result of the binary AND is non-zero: bool is_dangerous = (country->flags & dangerous_mask) != 0; – Tyler Kropp Commented Oct 8, 2020 at 14:26
Add a comment | 39

By the way, the next C++ version will support user defined literals. They are already included into the working draft. This allows that sort of stuff (let's hope i don't have too many errors in it):

template<char... digits> constexpr int operator "" _b() { return conv2bin<digits...>::value; } int main() { int const v = 110110110_b; }

conv2bin would be a template like this:

template<char... digits> struct conv2bin; template<char high, char... digits> struct conv2bin<high, digits...> { static_assert(high == '0' || high == '1', "no bin num!"); static int const value = (high - '0') * (1 << sizeof...(digits)) + conv2bin<digits...>::value; }; template<char high> struct conv2bin<high> { static_assert(high == '0' || high == '1', "no bin num!"); static int const value = (high - '0'); };

Well, what we get are binary literals that evaluate fully at compile time already, because of the "constexpr" above. The above uses a hard-coded int return type. I think one could even make it depend on the length of the binary string. It's using the following features, for anyone interested:

  • Generalized Constant Expressions.
  • Variadic Templates. A brief introduction can be found here
  • Static Assertions (static_assert)
  • User defined Literals

Actually, current GCC trunk already implements variadic templates and static assertions. Let's hope it will support the other two soon. I think C++1x will rock the house.

Share Improve this answer Follow edited Feb 12, 2009 at 5:08 answered Feb 11, 2009 at 18:20 Johannes Schaub - litb's user avatar Johannes Schaub - litbJohannes Schaub - litb 506k131 gold badges917 silver badges1.2k bronze badges 10
  • 1 Very nice example, it's what I had in mind in my shorter answer but you fleshed it out very nicely! – Motti Commented Apr 27, 2009 at 11:39
  • According to the last link, shouldn't it be constexpr int operator"_b"()? – NikiC Commented Jul 22, 2010 at 15:19
  • 4 What do you mean by the next C++ version? Your answer is from 2009 is it C++11? – Wolf Commented Jun 26, 2014 at 11:52
  • 2 I found user literals being integrated into C++11: User-defined literals (since C++11) - cppreference.com – Wolf Commented Jun 26, 2014 at 12:00
  • 1 @ThomasWeller at 2009 the next C++ version was C++11. If I said "C++11 will ...", I would be confronted with english syntax and replace it with "C++11 has...". And rewrite all my other answers this way and change future into past. I'm too tired for that, I hope you understand :) You are welcome to edit and fix my answer though :) – Johannes Schaub - litb Commented Sep 10, 2016 at 21:36
| Show 5 more comments 16

The C++ Standard Library is your friend:

#include <bitset> const std::bitset <32> has_nukes( "00000000000000000000000000000001" ); Share Improve this answer Follow answered Feb 11, 2009 at 15:34 anonanon 2
  • 3 Ha, that's nice. The only downside seems to be, for the purists among us, that it has to parse a string at runtime just to assign the value. With BOOST_BINARY, which someone here pointed to, that's not necessary. – Frank Commented Feb 11, 2009 at 15:57
  • 5 or alternatively with const int has_nukes = bitset<32>("10101101").to_ulong(); – Johannes Schaub - litb Commented Feb 11, 2009 at 18:39
Add a comment | 14

GCC supports binary constants as an extension since 4.3. See the announcement (look at the section "New Languages and Language specific improvements").

Share Improve this answer Follow answered Feb 11, 2009 at 19:21 bluebrother's user avatar bluebrotherbluebrother 8,8561 gold badge21 silver badges22 bronze badges 3
  • +1 Why does nobody realise this? Their loss -- it's awesome! Go GCC. – Engineer Commented Feb 1, 2012 at 18:40
  • 1 That's not useful if your code will be compiled by something other than gcc (or some gcc-compatible implementation). – Keith Thompson Commented May 20, 2013 at 21:34
  • It works in clang too (although you get a warning with -pedantic) – Joe the Person Commented Feb 5, 2019 at 19:39
Add a comment | 13

You can use << if you like.

int hasNukes = 1; int hasBioWeapons = 1 << 1; int hasChemWeapons = 1 << 2; Share Improve this answer Follow answered Feb 11, 2009 at 15:28 Jon B's user avatar Jon BJon B 51.8k31 gold badges136 silver badges163 bronze badges 1
  • 2 Thanks, that's even nicer than the 0b0000... option. – Frank Commented Feb 11, 2009 at 15:32
Add a comment | 9

This discussion may be interesting... Might have been, as the link is dead unfortunately. It described a template based approach similar to other answers here.

And also there is a thing called BOOST_BINARY.

Share Improve this answer Follow edited Jun 9, 2015 at 11:55 answered Feb 11, 2009 at 15:32 Anonymous's user avatar AnonymousAnonymous 18.6k2 gold badges41 silver badges64 bronze badges 2
  • 1 The link to the discussion is broken. Could you please summarize it here instead? – Rob Kennedy Commented Aug 28, 2014 at 22:18
  • You've got a dead link with no context in your answer so it is now useless, at least your second link is googleable... – Troyseph Commented Jun 9, 2015 at 11:25
Add a comment | 9

The term you want is binary literals

Ruby has them with the syntax you give.

One alternative is to define helper macros to convert for you. I found the following code at http://bytes.com/groups/c/219656-literal-binary

/* Binary constant generator macro * By Tom Torfs - donated to the public domain */ /* All macro's evaluate to compile-time constants */ /* *** helper macros *** */ /* turn a numeric literal into a hex constant * (avoids problems with leading zeroes) * 8-bit constants max value 0x11111111, always fits in unsigned long */ #define HEX_(n) 0x##n##LU /* 8-bit conversion function */ #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 *** / /* for upto 8-bit binary constants */ #define B8(d) ((unsigned char) B8_(HEX_(d))) /* for upto 16-bit binary constants, MSB first */ #define B16(dmsb, dlsb) (((unsigned short) B8(dmsb) << 8) \ | B8(dlsb)) /* for upto 32-bit binary constants, MSB first */ #define B32(dmsb, db2, db3, dlsb) (((unsigned long) B8(dmsb) << 24) \ | ((unsigned long) B8( db2) << 16) \ | ((unsigned long) B8( db3) << 8) \ | B8(dlsb)) /* Sample usage: * B8(01010101) = 85 * B16(10101010,01010101) = 43605 * B32(10000000,11111111,10101010,01010101) = 2164238933 */ Share Improve this answer Follow edited Jan 5, 2018 at 7:35 pmttavara's user avatar pmttavara 7589 silver badges16 bronze badges answered Feb 11, 2009 at 15:37 Mark Pim's user avatar Mark PimMark Pim 10.1k7 gold badges42 silver badges59 bronze badges Add a comment | 4

The next version of C++, C++0x, will introduce user defined literals. I'm not sure if binary numbers will be part of the standard but at the worst you'll be able to enable it yourself:

int operator "" _B(int i); assert( 1010_B == 10); Share Improve this answer Follow answered Feb 11, 2009 at 15:48 Motti's user avatar MottiMotti 114k55 gold badges194 silver badges273 bronze badges Add a comment | 4

I write binary literals like this:

const int has_nukes = 0x0001; const int has_bio_weapons = 0x0002; const int has_chem_weapons = 0x0004;

It's more compact than your suggested notation, and easier to read. For example:

const int upper_bit = 0b0001000000000000000;

versus:

const int upper_bit = 0x04000;

Did you notice that the binary version wasn't an even multiple of 4 bits? Did you think it was 0x10000?

With a little practice hex or octal are easier for a human than binary. And, in my opinion, easier to read that using shift operators. But I'll concede that my years of assembly language work may bias me on that point.

Share Improve this answer Follow edited Feb 11, 2009 at 21:30 answered Feb 11, 2009 at 18:27 Darron's user avatar DarronDarron 21.6k5 gold badges51 silver badges54 bronze badges 1
  • 0b0001000000000000000 != 0x04000. I think you meant 0b100000000000000 – hlscalon Commented Apr 24, 2015 at 20:58
Add a comment | 3

As an aside:

Especially if you're dealing with a large set, instead of going through the [minor] mental effort of writing a sequence of shift amounts, you can make each constant depend on the previously defined constant:

const int has_nukes = 1; const int has_bio_weapons = has_nukes << 1; const int has_chem_weapons = has_bio_weapons << 1; const int has_nunchuks = has_chem_weapons << 1; // ...

Looks a bit redundant, but it's less typo-prone. Also, you can simply insert a new constant in the middle without having to touch any other line except the one immediately following it:

const int has_nukes = 1; const int has_gravity_gun = has_nukes << 1; // added const int has_bio_weapons = has_gravity_gun << 1; // changed const int has_chem_weapons = has_bio_weapons << 1; // unaffected from here on const int has_nunchuks = has_chem_weapons << 1; // ...

Compare to:

const int has_nukes = 1 << 0; const int has_bio_weapons = 1 << 1; const int has_chem_weapons = 1 << 2; const int has_nunchuks = 1 << 3; // ... const int has_scimatar = 1 << 28; const int has_rapier = 1 << 28; // good luck spotting this typo! const int has_katana = 1 << 30;

And:

const int has_nukes = 1 << 0; const int has_gravity_gun = 1 << 1; // added const int has_bio_weapons = 1 << 2; // changed const int has_chem_weapons = 1 << 3; // changed const int has_nunchuks = 1 << 4; // changed // ... // changed all the way const int has_scimatar = 1 << 29; // changed *sigh* const int has_rapier = 1 << 30; // changed *sigh* const int has_katana = 1 << 31; // changed *sigh*

As an aside to my aside, it's probably equally hard to spot a typo like this:

const int has_nukes = 1; const int has_gravity_gun = has_nukes << 1; const int has_bio_weapons = has_gravity_gun << 1; const int has_chem_weapons = has_gravity_gun << 1; // oops! const int has_nunchuks = has_chem_weapons << 1;

So, I think the main advantage of this cascading syntax is when dealing with insertions and deletions of constants.

Share Improve this answer Follow edited Feb 12, 2009 at 5:14 answered Feb 12, 2009 at 5:09 Ates Goral's user avatar Ates GoralAtes Goral 140k27 gold badges141 silver badges190 bronze badges Add a comment | 3

If you want to use bitset, auto, variadic templates, user-defined literals, static_assert, constexpr, and noexcept try this:

template<char... Bits> struct __checkbits { static const bool valid = false; }; template<char High, char... Bits> struct __checkbits<High, Bits...> { static const bool valid = (High == '0' || High == '1') && __checkbits<Bits...>::valid; }; template<char High> struct __checkbits<High> { static const bool valid = (High == '0' || High == '1'); }; template<char... Bits> inline constexpr std::bitset<sizeof...(Bits)> operator"" bits() noexcept { static_assert(__checkbits<Bits...>::valid, "invalid digit in binary string"); return std::bitset<sizeof...(Bits)>((char []){Bits..., '\0'}); }

Use it like this:

int main() { auto bits = 0101010101010101010101010101010101010101010101010101010101010101bits; std::cout << bits << std::endl; std::cout << "size = " << bits.size() << std::endl; std::cout << "count = " << bits.count() << std::endl; std::cout << "value = " << bits.to_ullong() << std::endl; // This triggers the static_assert at compile-time. auto badbits = 2101010101010101010101010101010101010101010101010101010101010101bits; // This throws at run-time. std::bitset<64> badbits2("2101010101010101010101010101010101010101010101010101010101010101bits"); }

Thanks to @johannes-schaub-litb

Share Improve this answer Follow answered Oct 26, 2011 at 19:05 emsr's user avatar emsremsr 16.3k7 gold badges51 silver badges63 bronze badges Add a comment | 2

Java doesn't support binary literals either, unfortunately. However, it has enums which can be used with an EnumSet. An EnumSet represents enum values internally with bit fields, and presents a Set interface for manipulating these flags.

Alternatively, you could use bit offsets (in decimal) when defining your values:

const int HAS_NUKES = 0x1 << 0; const int HAS_BIO_WEAPONS = 0x1 << 1; const int HAS_CHEM_WEAPONS = 0x1 << 2; Share Improve this answer Follow edited Feb 11, 2009 at 15:43 answered Feb 11, 2009 at 15:31 Zach Scrivena's user avatar Zach ScrivenaZach Scrivena 29.5k12 gold badges65 silver badges73 bronze badges 1
  • Java now supports binary literals! – Troyseph Commented Jun 9, 2015 at 11:28
Add a comment | 2

Binary literals are part of the C++ language since C++14. It’s literals that start with 0b or 0B. Reference

Share Improve this answer Follow edited Apr 15, 2022 at 14:16 cigien's user avatar cigien 60k11 gold badges80 silver badges121 bronze badges answered Apr 15, 2022 at 10:54 Konstantin Burlachenko's user avatar Konstantin BurlachenkoKonstantin Burlachenko 5,6173 gold badges45 silver badges41 bronze badges 2
  • @cigien Thanks for providing reference, but sometimes people in stackoverflow claim that it violates principles of stackoverflow – Konstantin Burlachenko Commented Apr 15, 2022 at 17:56
  • 1 Link-only answers, i.e. answers that would have no useful information if the link dies, are inappropriate. Also, links that are irrelevant to the post, or links that are meant to promote a product/tool/etc (i.e. spam) are also inappropriate. However, none of the above applies to this answer. Specifically, including cppreference links in otherwise useful answers is always welcome, since it's an official reference page. – cigien Commented Apr 15, 2022 at 18:01
Add a comment | 1

There's no syntax for literal binary constants in C++ the way there is for hexadecimal and octal. The closest thing for what it looks like you're trying to do would probably be to learn and use bitset.

Share Improve this answer Follow answered Feb 11, 2009 at 17:38 Bill the Lizard's user avatar Bill the LizardBill the Lizard 405k210 gold badges572 silver badges889 bronze badges Add a comment | 1

Another method:

template<unsigned int N> class b { public: static unsigned int const x = N; typedef b_<0> _0000; typedef b_<1> _0001; typedef b_<2> _0010; typedef b_<3> _0011; typedef b_<4> _0100; typedef b_<5> _0101; typedef b_<6> _0110; typedef b_<7> _0111; typedef b_<8> _1000; typedef b_<9> _1001; typedef b_<10> _1010; typedef b_<11> _1011; typedef b_<12> _1100; typedef b_<13> _1101; typedef b_<14> _1110; typedef b_<15> _1111; private: template<unsigned int N2> struct b_: public b<N << 4 | N2> {}; }; typedef b<0> _0000; typedef b<1> _0001; typedef b<2> _0010; typedef b<3> _0011; typedef b<4> _0100; typedef b<5> _0101; typedef b<6> _0110; typedef b<7> _0111; typedef b<8> _1000; typedef b<9> _1001; typedef b<10> _1010; typedef b<11> _1011; typedef b<12> _1100; typedef b<13> _1101; typedef b<14> _1110; typedef b<15> _1111;

Usage:

std::cout << _1101::_1001::_1101::_1101::x;

Implemented in CityLizard++ (citylizard/binary/b.hpp).

Share Improve this answer Follow edited Feb 17, 2011 at 2:26 answered Feb 14, 2011 at 12:41 Sergey Shandar's user avatar Sergey ShandarSergey Shandar 2,38718 silver badges27 bronze badges Add a comment | 1

I agree that it's useful to have an option for binary literals, and they are present in many programming languages. In C, I've decided to use a macro like this:

#define bitseq(a00,a01,a02,a03,a04,a05,a06,a07,a08,a09,a10,a11,a12,a13,a14,a15, \ a16,a17,a18,a19,a20,a21,a22,a23,a24,a25,a26,a27,a28,a29,a30,a31) \ (a31|a30<< 1|a29<< 2|a28<< 3|a27<< 4|a26<< 5|a25<< 6|a24<< 7| \ a23<< 8|a22<< 9|a21<<10|a20<<11|a19<<12|a18<<13|a17<<14|a16<<15| \ a15<<16|a14<<17|a13<<18|a12<<19|a11<<20|a10<<21|a09<<22|a08<<23| \ a07<<24|a06<<25|a05<<26|a04<<27|a03<<28|a02<<29|a01<<30|(unsigned)a00<<31)

The usage is pretty much straightforward =)

Share Improve this answer Follow answered Apr 8, 2014 at 15:14 punpcklbw's user avatar punpcklbwpunpcklbw 1191 silver badge5 bronze badges Add a comment | 1

One, slightly horrible way you could do it is by generating a .h file with lots of #defines...

#define b00000000 0 #define b00000001 1 #define b00000010 2 #define b00000011 3 #define b00000100 4

etc. This might make sense for 8-bit numbers, but probably not for 16-bit or larger.

Alternatively, do this (similar to Zach Scrivena's answer):

#define bit(x) (1<<x) int HAS_NUKES = bit(HAS_NUKES_OFFSET); int HAS_BIO_WEAPONS = bit(HAS_BIO_WEAPONS_OFFSET); Share Improve this answer Follow edited Mar 23, 2017 at 11:13 answered Feb 11, 2009 at 15:37 Rocketmagnet's user avatar RocketmagnetRocketmagnet 5,8498 gold badges41 silver badges50 bronze badges 2
  • Arduino does this for all values up to 8-bits, btw. github.com/arduino/Arduino/blob/master/hardware/arduino/avr/… – Billy Donahue Commented Jan 19, 2018 at 6:25
  • updated arduino link:github.com/arduino/ArduinoCore-avr/blob/… – Billy Donahue Commented Nov 4, 2019 at 6:21
Add a comment | 0

Maybe less relevant to binary literals, but this just looks as if it can be solved better with a bit field.

struct DangerCollection : uint32_t { bool has_nukes : 1; bool has_bio_weapons : 1; bool has_chem_weapons : 1; // ..... }; DangerCollection arsenal{ .has_nukes = true, .has_bio_weapons = true, .has_chem_weapons = true, // ... }; if(arsenal.has_bio_weapons){ std::cout << "BIO!!" }

You would still be able to fill it with binary data, since its binary footprint is just a uint32. This is often used in combination with a union, for compact binary serialisation:

union DangerCollectionUnion { DangerCollection collection; uint8_t data[sizeof(DangerCollection)]; }; DangerCollectionUnion dc; std::memcpy(dc.data, bitsIGotFromSomewhere, sizeof(DangerCollection)); if (dc.collection.has_bio_weapons) { // ....

In my experience less error prone and easy to understand what's going on.

Share Improve this answer Follow answered Nov 18, 2021 at 19:39 Tates's user avatar TatesTates 891 silver badge1 bronze badge Add a comment |

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid …

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.

Draft saved Draft discarded

Sign up or log in

Sign up using Google Sign up using Email and Password Submit

Post as a guest

Name Email

Required, but never shown

Post Your Answer Discard

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.

  • Featured on Meta
  • We’re (finally!) going to the cloud!
  • More network sites to see advertising test [updated with phase 2]

Linked

252 Can I use a binary literal in C or C++? 54 Why doesn't C have binary literals? 14 C++ binary constant/literal 14 Template Meta-programming with Char Arrays as Parameters 12 Are user-defined-literals resolved at compile-time or runtime? 9 How to get smallest variable with C++11 user defined literals 4 bitwise operations in c++, how to actually use it? 0 Printing std::bitset in C++11 1 the best way define a mask -2 Wrong result when XOR'ing two std::bitset See more linked questions 153 How do I write a short literal in C++? 14 How to write a string literal which contains double quotes 252 Can I use a binary literal in C or C++? 0 What is a Binary Literal? 0 binary string implementation in C++ 1 How to define a value in binary bit way in C++? 1 How to create an array of binary literals 1 Binary data type C++ 3 Binary Literals in C++ 1 C++ Binary Literal

Hot Network Questions

  • Can .zshrc be modified automatically by other programs, installers, etc.?
  • Minimal Rules of Style for a Rough Draft
  • Routing fastest route with weighted paths in QGIS
  • How to delete faces that intersect an edge with geometry nodes?
  • Converting Line Segments to Lines
  • Burned washing machine plug
  • What could be the potential risk of installing this "ATB" handlebar on a road bike?
  • Why do I have to reboot to activate a kernel upgrade even though live kernel updates are enabled?
  • What is the name of the lady with the white blouse?
  • Looking for short story about detectives investigating a murder in the future
  • Polynomial.java - a Java class for dealing with polynomials with BigDecimal coefficients
  • Deutsche Bahn Berlin: can I use a different departure station?
  • How do I remove a hat from my horse?
  • Hearing the cry of a baby - abandoning practice for action?
  • Typesetting phantom contents in nicematrix
  • What happened to the lifeboats in Star Trek: First Contact?
  • range has lost one leg of 220
  • How to inherit material when using geometry nodes?
  • Find the one sentence that is wrong in the following proof.
  • How do I go about rebranding a fully deleted project that used to have a GNU General Public License v3.0 but is now fully inaccessible
  • Are prenups legally binding in England?
  • List of all sequences with certain properties
  • The sum of multiple irrational numbers can be rational, even when they're not conjugates. Is this normal?
  • Map or Thread operation for list
more hot questions Question feed Subscribe to RSS Question feed

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

lang-cpp

Từ khóa » C 0b0000