0
$\begingroup$

I tested on wolfram alpha and rust language and the log(0xff, 0xffff), is not 2 but 0xff power 2 equals 0xffff. The result is 2.00141... Why does this happen?

I have a 4 byte number and I want to get the amount of bytes that it needs (e.g. lower than 0xff needs 1 byte, lower than 0xffff needs two bytes, etc.). I thought logarithm was the right way to solve this.

$\endgroup$
1
  • 2
    $\begingroup$ Do not confuse 0xff which is $255 = 2^8-1$ with $2^8$ and 0xffff which is $2^{16}-1$ with $2^{16}$. Note that $2^8$ when squared results in $2^{16}$ but $(2^8-1)^2$ results in $2^{16}-2^9+1$, not $2^{16}-1$ $\endgroup$
    – JMoravitz
    Commented Nov 14, 2019 at 19:11

1 Answer 1

1
$\begingroup$

If $\log_{2^8-1}(2^{16}-1)$ was $2$, it would mean that $(2^8-1)^2=2^{16}-1$ which is obviously not the case. ($255^2\not= 65535$)

Why not just initialise a counter to $0$, and then shift your value by 8 bits (up to $4$ times), increasing the counter every time you get a nonzero result?

If you insist on logarithms (even though they are probably too slow for what you need), take the base 0x100 = $256$. Then take the integer part and add $1$ - this will give you the number of bytes needed. In other words, the formula is, for $x\ne 0$: $d=\lfloor\log_{256}(x)\rfloor+1$.

Example: $\lfloor\log_{256}(\text{0x72A943})\rfloor+1=\lfloor2.855\ldots\rfloor+1=2+1=3$.

$\endgroup$
1
  • $\begingroup$ Too much computers make me miss that last digit :P Thank you. And you're probably right that it might be faster to do a for loop or 3 if statements instead of a logarithm $\endgroup$
    – dzervas
    Commented Nov 14, 2019 at 19:28

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .