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?
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.
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 ;)
Related
I want to add two large numbers in C++ using vectors. However, I can't find any way in which I could properly read them from a file, so I wanted to use a char array which will read the characters and, if they are digits convert them into an int variable of the vector.
Is there any way in which I could do this?
You can easily convert digits into the corresponding integer values, because char can be treated as numeric values. Assuming you got some input like
char input = getNextDigit();
You can do
int asInt = input - '0';
which works, if input is any digit from '0' to '9'.
You can use the atoi function. The given link has pretty clear examples on how to use it.
I hope this is what you were looking for!
UPD: whenever you deal with strings it is better to go one step up in terms of abstraction and don't work with arrays of char directly. std::string should be your first choice. Starting from C++11 atoi has an std::string version called stoi.
I was given the following assignment, but I do not understand exactly what is the problem exactly...
Write a program that reads a string consisting of a positive integer or a positive decimal number and converts the numbers to the number format.
from my perspective what is saying is that I need to read a string consisting of x integer/decimal and convert it to an integer or a double...is that right? it seems so easy because I can just use strtol() and strtod().
It depends on whether you are allowed to use the standard library functions or not. If so, then, yes, it is just as easy as you described. If not, you will have to parse the string looking for decimal points, minus signs, etc. and convert by your own algorithms.
I'm not writing an answer for you, but you basically your assignment asks to convert strings of form say :
"123"
"-321"
"+3219871230"
"0123"
to corresponding numbers.
Also, since this is an assignment your professor shouldn't be interested in seeing solutions using library functions strtod, strtol etc.
I'm learning a crypto class and one of the assignment asked us to xor a bunch of hex ciphertext and try to find the encrypted message.
I know that you can do '0x' in front of int or long to hold a hex value in a variable, but what if my message is this long:
271946f9bbb2aeadec111841a81abc300ecaa01bd8069d5cc91005e9fe4aad6e04d513e96d99de2569bc5e50eeeca709b50a8a987f4264edb6896fb537d0a716132ddc938fb0f836480e06ed0fcd6e9759f40462f9cf57f4564186a2c1778f1543efa270bda5e933421cbe88a4a52222190f471e9bd15f652b653b7071aec59a2705081ffe72651d08f822c9ed6d76e48b63ab15d0208573a7eef027
I would get an overflow. Is there a way to put the whole message into one variable? I could split the message into subparts, but I prefer it to be in variable instead of many (if that is possible). I tried to use string to hold the massage, but how can I use the operator, '^', for xor?
Or is there a more simple technique that I do not know of?
Thanks
For something like this, you'd typically use a string or a vector<char> to hold the data. You can't use the entire string/vector as an operand to ^, but you can apply it one byte at a time.
If you want to simplify the rest of the code, you could create a class that overloaded operator^ to do a byte-wise XOR, so your code would look something like result = key ^ message;.
You could use an array of, well, any size integer, and apply your operators to it an element at a time (which will probably be a bit more efficient than an array of characters). #JerryCoffin's idea of wrapping it inside a class w/ an overloaded operator is a good one, regardless of the actual representation you use.
Put it in a separate text file
read the file into a buffer
convert ascii chars to hex values
Jerry & Scott have sound suggestions. Another option is to use an existing library: for example, the GNU GMP arbitrary-precision maths library at http://gmplib.org, which supports XOR (see http://gmplib.org/manual/Integer-Logic-and-Bit-Fiddling.html#Integer-Logic-and-Bit-Fiddling) and a "scanf" style function to read in hex (see http://gmplib.org/manual/Formatted-Input-Strings.html#Formatted-Input-Strings), and explicitly aims to provide excellent support for cryptography.
I've been assigned a problem I simply do not understand. I know that I need to use a cin function (like cin.get()), but I'm not sure which one I need or how to use it in this circumstance.
I need to create an insertion and extraction operator that reads (and writes) 3 pieces of data. All of the data is of the type int. For context, the data is the whole part of a fraction, the numerator, and the denominator. The data needs to be delimited by spaces, and the operators will be used for file input and output.
What I really want to know is which cin function I should use, and what the particular syntax should be considering I want to store the value in an integer.
Thanks in advance!
With cin, you can just read data using something like this:
int wholepart,numer,denom;
cin>>wholepart>>numer>>denom;
This would read 3 integers into wholepart, numer and denom respectively. It will skip over whitespace separating the integers.
The normal operator>> for ints expects the data to be separated by whitespace, so you should be able to just use it and interpret the results as you see fit.
Does anyone know of a library for encoding a number of primitive types (like integers, floats, strings, etc) into a string but preserving the lexicographical order of the types?
Ideally, I'm looking for a C++ library, but other languages are fine too. Also, one can assume that the format does not need to be encoded in the string itself (that is, if it's int64/string/float then the encoded string does not need to encode this information, only encoding the data is enough).
Take a look at this paper ("Efficient Lexicographic Encoding of Numbers") which shows how to represent any numeric type as a string such the lexicographic order of the strings is the same as the numerical order of the underlying numbers. It copes with arbitrary length numbers.
http://www.zanopha.com/docs/elen.pdf
I had the problem of converting integers and longs to strings which preserve ordering. And since I was working in Java, I only had signed types.
My algorithm was very simple:
Flip the sign bit (toEncode ^ Long.MAX_VALUE for longs) otherwise negative numbers are greater than positive numbers.
Do a modified base64 encoding of the bytes. Unfortunately, the normal base64 encoding doesn't preserve ordering; the special characters (+ and /) are after the numbers which are after the characters. This is completely backwards from ASCII. My modified encoding simply uses the ASCII ordering. (To make it clear it wasn't normal base64, I changed the special chars to - and _ with ~ as the padding. These are still useable within an URL, which was another a constraint I had.)
BTW ...
In Amazon Web Service's SimpleDB, all data are stored as strings. Its select comparators use lexicographic ordering. AWS provides utility functions to encode various types. For example, integers are encoded knowing the range of the integers apriori and adjusting via zero-padding and offsets (e.g. for negative integers). You could of course give it the worst possible range.
See "Query 201: Tips and Tricks for Amazon SimpleDB Query" - http://aws.amazon.com/articles/1232
http://typica.s3.amazonaws.com/com/xerox/amazonws/sdb/DataUtils.html
Just write numeric values in a fixed column width with leading zeros, and strings as normal. So like this:
0.1 -> 0000000.1000000
123 -> 0000123.0000000
foo -> foo
X -> X
Then you can sort as text (e.g. Unix sort without -n). How about that?