why use 0xffff over 65535

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?

4 Answers

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.

3

If your code is doing binary manipulations, using hex values like this is a lot easier to understand in the context compared with decimal; although I wouldn't consider mt_rand as one of those contexts (especially as the lower bound is decimal and it's only the upper bound that's hex in your example)

3

It's just the hexadecimal notation for 65535. There is no important difference between the two in the context you provided, but it's easier to remember "0, x and four f characters" than 65535.

2

0xffff is a hexadecimal number. The 0x only tells you that the value after the 0x is hexadecimal. Hexadecimal has 16 digits from 0 to 9 and from a to f (which means, a = 10, b = 11, c = 12, d = 13, e = 14, f = 15 in a hexadecimal number).

To calculate the decimal value of a hexadecimal number you have to multiply the value of the digits with 16 to the power of the digits place in the number.

Example:

ffff = (15*16^3) + (15*16^2) + (15*16^1) + (15*16^0) = 65535

In the above case, f has a value of 15 and it is in the place 0, 1, 2, and 3 of the number. Then in the following example, hexadecimal 3, 4, and 6 behave with an equivalent decimal value, and a has a value of 10.

34a6 = (3*16^3) + (4*16^2) + (10*16^1) + (6*16^0) = 13478

Hope that could help

1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like