user4271704
user4271704

Reputation: 763

How to convert a decimal integer to bytes with php?

I need to get how much bytes is a decimal integer with php. For example how can I know if 256,379 is 3-bytes with php? I need a php function to pass 256,379 as input and get 3 as output. How can I have it?

Upvotes: 1

Views: 1144

Answers (2)

Evgeny
Evgeny

Reputation: 4010

You need calculate logarithm like this:

echo ceil( log ($nmber, 256) );

Upvotes: 2

user5751606
user5751606

Reputation:

The number of bytes needed to represent a number can be calculated like this:

echo getNumBytes(256379); // Output: 3
echo getNumBytes(25637959676); // Output 5

function getNumBytes($num) {
    $i = 1;
    do {
        $i++;
    } while(pow(256,$i) < $num);
    return $i;
}

Upvotes: 2

Related Questions