使用0x01而不是1作为整数变量的优点? [英] Advantage of using 0x01 instead of 1 for an integer variable?

查看:168
本文介绍了使用0x01而不是1作为整数变量的优点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我遇到了这样的一条线


$ b


public final static int DELETION_MASK = 0x01;

为什么它不像


public final static int DELETION_MASK = 1; / p>

使用除0xA以外的第一种方法是否有优势,并且上限十六进制可以轻松转换?在这种情况下,它只是一个代表1的常量。

传统上使用十六进制符号书写掩码,因为人类转换为二进制形式显然更容易。另一个常见的约定是在字段长度已知时包含前导零。例如。对于C int 字段,通常写入:

  #define MASK 0x0000ffff 

另外,十六进制常量向程序员表明它可能 一个位掩码或一个值,它将以某种方式涉及按位操作,应该专门处理。



作为奖励,十六进制符号也可以避免负数的问题: 0xffffffff 实际上是一个负数(确切地说 -1 )。而不是与符号和2的补码数字杂耍,你可以用十六进制指定掩码,并用它来完成。






从Java 7开始,您还可以使用 二进制文字 ,这使得人们更容易理解在位掩码中设置哪些位。而二进制文字可能会使用下划线

这意味着以下内容也是有效的:

  public final static int DELETION_MASK = 0b0000_0001; 


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.

解决方案

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;

这篇关于使用0x01而不是1作为整数变量的优点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆