Reputation: 6638
I have an size_t
variable nOffset
that holds a number of which I want to find out how many bytes are actually needed to store it. I guess the position of the MSB could also be used? This is my code so far (sizeof(size_t)
is 4):
int nLen = 0;
if (nOffset > 0xFFFFFF)
{
nLen = 4;
}
else if (nOffset > 0xFFFF)
{
nLen = 3;
}
else if (nOffset > 0xFF)
{
nLen = 2;
}
else
{
nLen = 1;
}
Upvotes: 2
Views: 2484
Reputation: 213306
Simply iterate through the data starting at the MSB, and mask each byte with 0xFF. To know which byte that is the MSB portabily, you have to use bit shifts.
In this snippet, i
is the number of bits to shift.
size_t i;
for(i=sizeof(data)*8; i!=0; i-=8)
{
if( (data >> (i-8)) & 0xFF)
{
break;
}
}
size_t bytes_to_copy = i / 8;
Upvotes: 0
Reputation: 957
If you are looking for how many bytes are taken by an int
variable, you can look into the limits.h
library, especially the INT_MIN
and INT_MAX
constants, then the number of bytes can be calculated.
If you are looking for how many bytes are needed to encode a certain integer, either
Use an algorithm, find the smallest power of 2 pow(2, N)
that's equal or larger than the integer, N would be the minimal number of bits. This is straightforward but has a small catch when the integer is negative, see https://softwareengineering.stackexchange.com/questions/239036/how-are-negative-signed-values-stored.
Or try to print out the bits of the number and count them, see C printing bits.
Upvotes: 2
Reputation: 25752
It is much easier to use a loop and predefined constants.
Divide the integer by the maximum value of a byte can represent plus one, until you get zero. The iteration count are the bytes.
The following outputs the number of bytes needed to store the precision of the integer:
size_t a = SIZE_MAX;
size_t bytes = 0;
while( a != 0 )
{
a /= ( 1u << CHAR_BIT );
bytes++;
}
Upvotes: 1
Reputation: 30489
You can use following builtin function in GCC
-- Built-in Function:
int __builtin_clz (unsigned int x)
Returns the number of leading 0-bits in X, starting at the most significant bit position. IfX
is0
, the result is undefined.-- Built-in Function:
int __builtin_clzl (unsigned long)
Similar to__builtin_clz
, except the argument type isunsigned long
.-- Built-in Function:
int __builtin_clzll (unsigned long long)
Similar to__builtin_clz
, except the argument type isunsigned long long
.
After finding number of leading zeros, it is simple calculations (num_bits = number of bits in int
- leading zeros) to find the number of bits required. You can change to number of bytes required with (num_bits + 7) / 8
.
Upvotes: 2