Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why use 0xffff over 65535

Tags:

php

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?

like image 850
fishcracker Avatar asked Oct 30 '12 10:10

fishcracker


3 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.

like image 79
Denis Kreshikhin Avatar answered Oct 19 '22 11:10

Denis Kreshikhin


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)

like image 33
Mark Baker Avatar answered Oct 19 '22 12:10

Mark Baker


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.

like image 6
Victor Stanciu Avatar answered Oct 19 '22 13:10

Victor Stanciu