Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the magic number in boost::hash_combine specified in hex

Tags:

c++

hash

boost

The magic number in this case is 0x9e3779b9, which in base 10 is 2654435769. Is there any reason why the code

seed ^= hash_value(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2); 

uses the hex representation instead of the base-10 representation? Would the functionality remain identical if 2654435769 was substituted for 0x9e3779b9 in the code?

like image 873
1110101001 Avatar asked Nov 02 '14 23:11

1110101001


1 Answers

Literals are literals and different representations of the same literal are... literally identical.

However, expressions (literal or not) also have a type.

The equivalent literal would have been 2654435769u (note the type suffix making it unsigned).

Look at this simple test Live On Coliru

  • 0x9e3779b9 has type unsigned int (32 bit) and
  • 2654435769 has type long (64 bit)
  • 2654435769u has type unsigned int (32 bit) again

As you can see, the hex representation favours unsigned and the decimal representation favours signed, making the type bigger¹.


¹ native integer sizes are implementation defined

(Beyond types, one could argue that maybe, perhaps, bit-distribution is slightly more apparent in hex, octal or ultimately binary representations)

like image 151
sehe Avatar answered Nov 14 '22 23:11

sehe