Since it was mentioned that speed is a big factor, it would be better to use bitwise operations.
Look at the ASCII table:
- The character
'0'
is 0x30
or 00110000
in binary format. - The character
'1'
is 0x31
or 00110001
in binary format.
Only the last bit of a character is different. Thus, we can confidently say that executing a bitwise OR on the characters themselves will lead to the creation of the correct character.
Another important thing we can do β to optimize speed β is to use a StringBuilder
initialized to the original capacity of our string. Or even better: we can reuse StringBuilder
for several operations, although we must ensure that StringBuilder
has sufficient capacity.
Given these optimizations, we can make this method:
string BinaryStringBitwiseOR(string a, string b, StringBuilder stringBuilder = null) { if (a.Length != b.Length) { throw new ArgumentException("The length of given string parameters didn't match"); } if (stringBuilder == null) { stringBuilder = new StringBuilder(a.Length); } else { stringBuilder.Clear().EnsureCapacity(a.Length); } for (int i = 0; i < a.Length; i++) { stringBuilder.Append((char)(a[i] | b[i])); } return stringBuilder.ToString(); }
Note that this will work for all bit operations that you would like to perform in your lines, you only need to change the |
.
source share