-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 
drake12
  • 9
  • 3
  • Just use `std::bitset` – Slava Oct 13 '17 at 17:14
  • Possible duplicate of [Convert binary format string to int, in C](https://stackoverflow.com/questions/2343099/convert-binary-format-string-to-int-in-c) – NineBerry Oct 13 '17 at 17:18
  • @NineBerry in C++ it can be done much simpler that writing a loop explicitly – Slava Oct 13 '17 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. – NineBerry Oct 13 '17 at 17:19
  • "take off leading zeros". There is no such thing as leading zeroes in integer represantation, only in string representation. – Sani Huttunen Oct 13 '17 at 17:19
  • @Slava I would suggest using the answer that uses strtol. – NineBerry Oct 13 '17 at 17:20
  • @NineBerry you may suggest to look there, but I do not think that answer for C makes this question duplicate. It can be and should be done differently in C++. – Slava Oct 13 '17 at 17:22

1 Answers1

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;
Beached
  • 1,608
  • 15
  • 18
  • 1
    Note that [binary literals](http://en.cppreference.com/w/cpp/language/integer_literal) are introduced in C++14 – Kevin Oct 13 '17 at 17:21
  • 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 – Beached Oct 13 '17 at 18:23