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>
A constant expression is an expression that can be evaluated at compile time. Constants of integral or enumerated type are required in several different situations, such as array bounds, enumerator values, and case labels. Null pointer constants are a special case of integral constants.
For example, if a program requires a “const”, but you're feeding it a “variable value”, which can be changed in the program or overwritten. So, use the keyword “const” before that variable to make it a constant and resolve the error.
1) The expression used in switch must be integral type ( int, char and enum). Any other type of expression is not allowed.
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.
std::bitset
's size can only be a compile-time known constant (constant expression) because it is an integral template parameter. Constant expressions include integral literals and/or constant integer variables initialized with constant expressions.
e.g.
std::bitset<4> q; //OK, 4 is a constant expression
const int x = 4;
std::bitset<x> qq; //OK, x is a constant expression, because it is const and is initialized with constant expression 4;
int y = 3;
const int z = y;
std::bitset<z> qqq; //Error, z isn't a constant expression, because even though it is const it is initialized with a non-constant expression
Use std::vector<bool>
or boost::dynamic_bitset
(link here) instead for dynamic (not known compile-time) size.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With