I’ve seen some PHP script which uses 0xffff in mt_rand(0, 0xffff)
. I do echo 0xffff;
and results to 65535. Is there any significance of using this 0xffff? And also what is that?
Advertisement
Answer
The hexadecimal notation 0xffff
makes it clear that all bits in the number are 1
. The 65535
is the same number, but the binary representation isn’t as obvious. It’s only a count number. So this way of writing numbers has different semantics.
For example, if you want to declare that the maximum value of some variable must be 65535, then it is best to state this like this:
$max_value = 65535;
Because that makes it easy for humans to compare it to other values like 65500 (< $max_value
) or 66000 (> $max_value
).
On the contrary for bit fields.
$default_state = 65535;
This does not tell me that all the bits are one (when in fact they are).
$default_state = 0xFFFF;
This does: Each hexadecimal digit stands for four bits, and an F
means four 1-bits. Therefore 0xFFFF
is 0b1111111111111111
in binary.
Hexadecimal notation is used when the programmer wants to make it clear that the binary representation is of importance, maybe more important than the precise numerical value.