-1

I'm having trouble converting a 16-bit std::string to an int that can hold the exact binary number of the string. I've been messing around with atoi and bitset but they converting to deciamls or take off leading zeros is there a way to do this

std::string str = "0011101100010101";
int num = 0;
.
.
.
num = 0011101100010101  // now equals 
7
  • Just use std::bitset Commented Oct 13, 2017 at 17:14
  • Possible duplicate of Convert binary format string to int, in C Commented Oct 13, 2017 at 17:18
  • @NineBerry in C++ it can be done much simpler that writing a loop explicitly Commented Oct 13, 2017 at 17:19
  • Note that integer variables hold numbers and not number representations, so there will be no leading zeros and the default output will output the number using the decimal system, not the binary system. Commented Oct 13, 2017 at 17:19
  • "take off leading zeros". There is no such thing as leading zeroes in integer represantation, only in string representation. Commented Oct 13, 2017 at 17:19

1 Answer 1

1

Use std::bitset

std::string str = "0011101100010101";
auto number = static_cast<uint16_t>(std::bitset<16>{ str }.to_ulong( ));

Or use a literal if you don't need a string

uint16_t b = 0b0011101100010101;
Sign up to request clarification or add additional context in comments.

2 Comments

Note that binary literals are introduced in C++14
That is true. The major compilers(g++, clang, msvc...) support it, plus many embedded ones have as an extension. I guess if you are stuck, but two ways there too

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.