2

I know it looks like a dummy question, but why senior developers use hexadecimal variables as the following code:

//  LIST OF GENDER FLAGS
//  ***********************************
//  HEX VALUES from (0x6d)[m] and (0x66)[f] are reserved for [GENDER] FLAGS
const GENDER_MALE       = 0x6d;
const GENDER_FEMALE     = 0x66;
//  **************************************************

PS: I found this code in a Yii project that's why i put Php in the tags

T.Baba
  • 649
  • 7
  • 17

2 Answers2

5

Hex numbers are very easy to be changed to binary. Each hexadecimal digit represents four binary digits (bits), and the primary use of hexadecimal notation is a human-friendly representation of binary-coded values in computing and digital electronics. That is why they are used by programmers.

1 byte = 255 in dec and 0xFF but for example

3 bytes = 16777215 in dec and 0xFFFFFF hex. Now you see that numbers are shorter because they have extra 6 digits(A-F).

When you define constant as hex you can get a lot of advantages. For example:

  1. You can use flags PHP function flags, how?
  2. Numbers in hex are easier to remember they are shorter.

Edit

Ad1. Flags obviously can be used with any other numeric system but hex makes them easier to understand and more readable.

Community
  • 1
  • 1
Robert
  • 19,800
  • 5
  • 55
  • 85
  • point 2 doesn't make sense to me. One of the benefits of class constants is so we don't _have_ to remember the numbers/values that they hold – Elias Van Ootegem Jul 08 '13 at 06:34
  • You can use flags defining them using a number of different notations, it doesn't have to be hex to be a flag. – deceze Jul 08 '13 at 06:34
  • Of course it doesn't need to be hex I agree but when you use hex it's easier and more readable. – Robert Jul 08 '13 at 06:37
  • In the OP's example, using the actual "m" and "f" would be *much more readable...* – deceze Jul 08 '13 at 06:39
  • i would just use `m` or `f` unless the context dictated that I do something specific. The hex values may mean something to an application that this code interacts with. – Orangepill Jul 08 '13 at 06:39
  • In such case it's better. Unless the software allows to be a sexual hybrid :) – Robert Jul 08 '13 at 06:42
2

It's a matter of taste. For one, using hexadecimal makes the constants line up nicely, and they are less typing.

Plus it looks cool.

Bart Friederichs
  • 33,050
  • 15
  • 95
  • 195