Reputation: 1817
In an Arbitrary system where 8bits != 1byte how to find number of bits = byte using programming?
What I have though of is keep on left shifting 1 till I get some wrong value. But how to code it?
Upvotes: 2
Views: 196
Reputation: 39013
Well, you can count if you want:
int bits = 0;
char byte = 1;
while(byte!=0)
{
bits++;
byte = byte << 1;
}
Each iteration finds about bit in byte
. When you run out of bits, byte becomes 0.
Using CHAR_BITS
is better, though.
Upvotes: 1
Reputation: 3107
You could use a template metaprogram for a compile-time determination of bit counts of primitive integer types.
This method relies on using an unsigned type because it simplifies things. This code finds the bit count of an unsigned char.
After determining the bit count of unsigned char, we can use the sizeof opeator to determine the bit count of any type under this "Arbitrary System."
#include <iostream>
template <unsigned char V=~unsigned char(0), int C=0>
struct bit_counter {
static const int count =
bit_counter<(V>>1),C+1>::count;
};
template <int C>
struct bit_counter<0, C> {
static const int count = C;
};
// use sizeof operator, along with the result from bit_counter
// to get bit count of arbitrary types.
// sizeof(unsigned char) always gives 1 with standard C++,
// but we check it here because this is some kind of
// "Arbitrary" version of the language.
template <typename T>
struct bit_count_of {
static const int value =
sizeof(T) * bit_counter<>::count / sizeof(unsigned char);
};
int main() {
std::cout << "uchar " << bit_counter<>::count << std::endl;
std::cout << "long " << bit_count_of<long>::value << std::endl;
std::cout << "double " << bit_count_of<double>::value << std::endl;
std::cout << "void* " << bit_count_of<void*>::value << std::endl;
}
Upvotes: 1
Reputation: 34563
You can use the CHAR_BIT
macro defined in the <climits>
header. It's a compile-time constant, so you don't have to do anything to figure it out at runtime.
Upvotes: 8