bitwise OR on strings
How can i do a Bitwise OR on strings?
A:
10001
01010
------
11011
Why on strings? T开发者_开发问答he Bits can have length of 40-50.Maybe this could be problematic on int ? Any Ideas ?
I would say std::bitset
is more than enough for your situation, but for more flexibility you can use boost::dynamic_bitset
. Here is an example on std::bitset
:
const size_t N = 64;
string a_str = "10001", b_str = "01010";
bitset<N> a(a_str), b(b_str);
bitset<N> c = a | b;
cout << c;
You should take a look at the C++ std::bitset
class, which does exactly what you want.
For each char
:
char result = (a - '0') | (b - '0') + '0';
Where a
and b
are two chars with ascii character 0 or 1 in them.
Why not just use a vector
of int
values? Doesn't the bitset
still use a byte per bit?
You can also use a vector
of bool
values, but this is also implementation specific.
Depending on whether you need storage efficiency or speed (or the utility of container methods that a couple of these approaches lack) you might profile to decide which approach to use.
This is similar to Andreas Brinck's answer, only it returns a full output string and can compare strings of different (arbitrary) lengths.
Example in C# (not near c++ compiler right now), but it should be simple to convert it to a language of your choice.
public static string BitwiseOr(string input1, string input2)
{
char[] inarr1 = (char[])input1.ToCharArray().Reverse().ToArray();
char[] inarr2 = (char[])input2.ToCharArray().Reverse().ToArray();
char[] outarr = new char[input1.Length > input2.Length ? input1.Length : input2.Length];
for (int i = 0; i < outarr.Length ; i++)
{
char c1 = i < input1.Length ? inarr1[i] : '0';
char c2 = i < input2.Length ? inarr2[i] : '0';
outarr[i] = (char)((c1 - '0') | (c2 - '0') + '0');
}
return new string((char[])outarr.Reverse().ToArray());
}
Of course this is only valid if you really need it to be in a string, if not you should (as suggested in other answers) use a vector or similar data type.
精彩评论