Reputation: 8137
I am getting a string of zeros and ones from a client API request. They are of a set length (28, in this case) and I want to convert them to a byte[]
or something similar, with the goal of storing these in SQL via EF Core and later using bitwise operators to compare them.
I can't seem to wrap my head around this one. I'm seeing a lot of posts/questions about converting characters to byte arrays, or byte arrays to strings, neither of which is what I need.
I need a "00111000010101010"
to become a literal binary 00111000010101010
I can use a ^
on.
Leading zeros would be fine if necessary, I think the length might be forced to be a multiple of 8?
Upvotes: 0
Views: 776
Reputation: 117084
You can binary string convert to an integer easily with this:
string source = "00111000010101010";
int number = Convert.ToInt32(source, 2); // The `2` is "base 2"
That gives: 28842
.
Then you can go one step further an convert to a byte array, if needed.
byte[] bytes = BitConverter.GetBytes(number);
Upvotes: 1