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?

I’m not sure whether the number of bytes used by PHP variables is available. Someone will no doubt correct me if I’m wrong. However, I very much doubt that any variable will use 3 bytes for anything. It will usually be 4, 8, 16 etc.

Can you clarify - do you want to know how many bytes the number can be stored in, or do you want to know how many bytes PHP is actually using to store the number? So if I had the number ‘1’ in a variable, would you want to know that the number can be stored in a single byte, or how many bytes PHP is actually using to store it?

This topic on another site has some discussion on various methods:

My guess would be that since the PHP engine is C, that it would be 2 or 4 bytes, though C does not have “decimal integers”

Type 		Storage size 	Value range
int 		2 or 4 bytes 	-32,768 to 32,767
				-2,147,483,648 to 2,147,483,647
unsigned int 	2 or 4 bytes 	0 to 65,535
				0 to 4,294,967,295
short 		2 bytes 	-32,768 to 32,767
unsigned short 	2 bytes 	0 to 65,535
long 		4 bytes 	-2,147,483,648 to 2,147,483,647
unsigned long 	4 bytes 	0 to 4,294,967,295

You can make use of dechex() and the fact that a one byte value is 2 characters long in hexadecimal:

function numBytes($num) {
    return ceil(strlen(dechex($num)) / 2);

echo numBytes(256379);

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.