How can I efficiently store binary codes? For certain fixed sizes, such as 32 bits, there are primitive types that can be used. But what if I my binary codes are much longer?
What is the fastest way to compute the Hamming distance between two binary codes?
Asked
Active
Viewed 1,208 times
3

Timothy Shields
- 75,459
- 18
- 120
- 173

mrgloom
- 20,061
- 36
- 171
- 301
-
What about std::bitset? – Niall Oct 02 '14 at 20:14
1 Answers
6
- Use
std::bitset<N>
, defined in the<bitset>
header, whereN
is the number of bits (not bytes). - Compute the Hamming distance between two binary codes
a
andb
using(a ^ b).count()
.

Timothy Shields
- 75,459
- 18
- 120
- 173
-
I don't understand what if use 30 bit codes I still can use 32bit integer?(maybe mask 2 first bits somehow)? – mrgloom Oct 02 '14 at 20:36
-
@mrgloom I would use this approach, profile it, and then only if you determine it is too slow look at doing something custom. My understanding is that a `std::bitset<30>` will only use 4 bytes of storage. – Timothy Shields Oct 02 '14 at 20:41
-
Nice Timothy, maybe you can help with [XOR bitset when 2D bitset is stored as 1D](http://stackoverflow.com/questions/40787731/xor-bitset-when-2d-bitset-is-stored-as-1d). – gsamaras Nov 24 '16 at 13:32