-4

Hello :) I'm trying to do a conversion of a string to an int using c++. I have tried using stol, stoll, and strtol functions and (maybe I was using them wrong) but they didn't seem to preserve my string in a literal sense.

Question: How would I go about literally converting a string containing 0s and 1s to an int so that my int is exactly like my string was.

Example:

string s = "00010011";
int digits = 0; // convert int to: digits = 00010011;

Appreciate it!

Michael
  • 5
  • 5
  • 3
    Possible duplicate of [Converting string of 1s and 0s into binary value](http://stackoverflow.com/questions/117844/converting-string-of-1s-and-0s-into-binary-value) – OldProgrammer Jul 14 '16 at 00:22
  • `int` stores numerical values. `10011` and `010011` are the same value. what youre describing is actually storing a string... so stick with your string – M.M Jul 14 '16 at 00:25
  • You probably aren't going to be able to preserve leading 0's when going from string -> int -> string. Any of the parsing functions you mentioned can create an integral rep of a string, within reason. – evaitl Jul 14 '16 at 00:28
  • @OldProgrammer not a duplicate, the person asking their question in your link is asking about a conversion from string to binary. – Michael Jul 14 '16 at 00:35
  • Actual numbers (int, for instance) don't have leading zeros, so it can't possibly look as you want. If you don't understand that integers (other than zero itself) can't start with a zero, you should probably go take a tutorial on basic number and math skills before writing code. – Ken White Jul 14 '16 at 00:36
  • @KenWhite Hey, thanks for the reply! At times I have a tendency to forget the basics -- all apart of learning, right?. I was looking for some suggestions on what to use if an int wasn't feasible here, thats all... Oh, and your tutorial suggestion was cute ;) – Michael Jul 14 '16 at 00:43
  • @M.M I'm thinking I'm going to have to stick with a string here. Thanks for the suggestion! – Michael Jul 14 '16 at 00:47

1 Answers1

0

Well, you can use std::bitset

string s = "00010011";
int digits = 0; // convert int to: digits = 00010011;

std::bitset<32> bst(s);
digits = static_cast<int>(bst.to_ulong());

To be more pedantic about size, instead of std::bitset<32>, you can do:

std::bitset<(sizeof(int) * 8)> bst(s);

To get back the string (well, not exactly):

std::string sp = std::bitset<32>(digits).to_string();

Additionally, to trim off the leading zeros from, sp:

auto x = sp.find_first_not_of('0');
if(x != string::npos)
    sp = sp.substr(x);
WhiZTiM
  • 21,207
  • 4
  • 43
  • 68