0

I want to do a binary operation in C++, namely XOR, on a binary input given by the user. The user will enter a sequence of zeros and ones only. How can I declare a variable to accept the input 1's and 0's as binary bits?

2
  • Read as string, and then verify the input. Commented Mar 26, 2014 at 19:54
  • I am actually a beginner in C++ and programming too. How can I verify the input? And for what purpose? Commented Mar 26, 2014 at 19:55

2 Answers 2

3

A convenient way is to use std::bitset. If you have a look at its constructors, there are options to construct a bit set from several data sources including std::string and C-style strings. Constructors validate the input and throw an exception in case invalid input is given.

You can then use its bitwise operators directly. XOR is operator^.

std::bitset is a fixed-size container, so you'll have to specify the maximum expected length as a constexpr value.

Sign up to request clarification or add additional context in comments.

3 Comments

I am not sure if bitset enables me to have the user specify the length of the input sequence?!
Will constexpr enable variable size sequence? The program I want to have asks the user to enter the length of the sequence before entering the sequence itself.
@MohamedAhmed As I said, the size is fixed, that is, known at compile time. This can be just a maximum, e.g. 256 bits. The user just enters the string representation that should not be longer than that.
0

get the sequence as a string, then use strtol with base 2 | or create your own function to convert the string into a integer (that's not really difficult) | or use the string directly (string[i]-'0')^...

Open your mind ;)

Comments

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.