string convert_binary_to_hex(string binary_value, int number_of_bits)
{
bitset<number_of_bits> set(binary_value);
ostringstream result;
result << hex << set.to_ulong() << endl;
return result.str();
}
In the above method, I am converting binary strings to hex strings. Since hex values are 4 bits, the number_of_bits
variable needs to be a multiple of 4 because the binary_value
could range anywhere from 4 bits to 256 bits with the application I'm writing.
How do I get bitset to take a variable size?
My imports:
#include <stdio.h>
#include <iostream>
#include <string>
#include <bitset>
#include <sstream>
You can't. Template parameters like that need to be known at compile time since the compiler will need to generate different code based on the values passed.
In this case you probably want to iterate through your string instead and build up the value yourself, e.g.
unsigned long result = 0;
for(int i = 0; i < binary_value.length(); ++i)
{
result <<= 1;
if (binary_value[i] != '0') result |= 1;
}
which also assumes that your result is shorter than a long, though, and won't accommodate a 256-bit value - but neither will your sample code. You'll need a big-number type for that.