Make your method a template as well if you can know the size at compile time, otherwise you'll need to use std::vector<bool>
which is actually specialized to use only one bit per bool
anyways, but you'll have to build the ulong
manually using or's and bitshifts.
//template version
template <size_t number_of_bits>
string convert_binary_to_hex(string binary_value) {
bitset<number_of_bits> set(binary_value);
ostringstream result;
result << hex << set.to_ulong() << endl;
return result.str();
}
But since you're already assuming that a ulong
will be large enough to hold the number of bits and since it won't make a difference if you have too many bits for the code you've given, why not just make it the size of a ulong
?
//reuses ulong assumption
string convert_binary_to_hex(string binary_value) {
bitset<sizeof(ulong)> set(binary_value);
ostringstream result;
result << hex << set.to_ulong() << endl;
return result.str();
}
Or else you can just have 2 functions, one that performs the actual conversion for a 4 bit number, and another that uses that function to build up arbitrary length numbers:
string convert_nibble_to_hex(string binary_value) {
bitset<4> set(binary_value);
ostringstream result;
result << hex << set.to_ulong() << endl;
return result.str();
}
string convert_binary_to_hex(string binary_value) {
//call convert_nibble_to_hex binary_value.length()/4 times
//and concatenate results
}