Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advantage of using 0x01 instead of 1 for an integer variable?

Tags:

Recently I came across a line like this

public final static int DELETION_MASK = 0x01;

why is it not like

public final static int DELETION_MASK = 1;

Is there any advantage in using the first approach other than 0xA and upper limit hexadecimals can be converted with ease?? In this case its just a constant representing 1.

like image 292
Ebbu Abraham Avatar asked Jun 30 '11 10:06

Ebbu Abraham


People also ask

What does 0x01 mean in C?

0x01 means 1—a one in the ones place—and 0x80 means 128—an 8 in the sixteens place. Those numbers refer to the lowest bit and highest bit in an eight-bit number, respectively. Shifting them gives masks for the individual bits in the byte.

Why do we use & 0xff?

In general, the & 0xff operation provides us with a simple way to extract the lowest 8 bits from a number. We can actually use it to extract any 8 bits we need because we can shift right any of the 8 bits we want to be the lowest bits. Then, we can extract them by applying the & 0xff operation.

Is 0x01 and 0x1 the same?

There's no difference between 0x01 and 0x1. In hexadecimal notation 0x1, 0x01, 0x001, and so on, they all means 1.


1 Answers

While there is not a difference in the code produced by the compiler, bit masks are traditionally written using the hexadecimal notation, because it's significantly easier for a human to convert to a binary form. Another common convention is to include the leading zeros when the length of the field is known. E.g. for a C int field, it's common to write:

#define MASK 0x0000ffff 

In addition, hexadecimal constants indicate to the programmer that it's probably a bit mask, or a value that will be somehow involved in bitwise operations and should probably be treated specially.

As a bonus, hexadecimal notations may also avoid issues with negative numbers: 0xffffffff is in fact a negative number (-1 to be exact). Rather than juggling with the sign and 2's-complement numbers you can just specify the mask in hexadecimal and be done with it.


Since Java 7 you can also use binary literals which makes it even easier for a human to understand which bits are set in a bit mask. And binary literals may make use of underscores to put the bits into separate groups.

That means that the following is also valid:

public final static int DELETION_MASK = 0b0000_0001; 
like image 193
thkala Avatar answered Oct 04 '22 07:10

thkala