C++ how to get length of bits of a variable? -


this question has answer here:

let's there variable int x. size 4 bytes, 32 bits.

then assign value var, x = 4567 (in binary 10001 11010111); now, in memory should this:

00000000 00000000 00010001 11010111

is there way length of bits matter. in excample, length of bits 13 (i marked them bold). if use sizeof (x) returns me 4 bytes, size of int. how size of bits represent number (without unnecessarily zero's follow after)?

warning: math ahead. if squeamish, skip ahead tl;dr.

what looking highest bit set. let's write out binary number 10001 11010111 means:

x = 1 * 2^(12) + 0 * 2^(11) + 0 * 2^(10) + ... + 1 * 2^1 + 1 * 2^0 

where * denotes multiplication , ^ exponentiation.

you can write

2^12 * (1 + a) 

where 0 < < 1 (to precise, a = 0/2 + 0/2^2 + ... + 1/2^11 + 1/2^12).

if take logarithm (base 2), let's denote log2, of number get

log2(2^12 * (1 + a)) = log2(2^12) + log2(1 + a) = 12 + b. 

since a < 1 can conclude 1 + < 2 , therefore b < 1.

in other words, if take log2(x) , round down significant power of 2 (in case, 12). since powers start counting @ 0, number of bits 1 more power, namely 13. so:

tl;dr:

the minimum number of bits needed represent number x given by

numberofbits = floor(log2(x)) + 1 

Comments

Popular posts from this blog

javascript - AngularJS custom datepicker directive -

javascript - jQuery date picker - Disable dates after the selection from the first date picker -