为什么使用十六进制常量? [英] Why use hexadecimal constants?

查看:289
本文介绍了为什么使用十六进制常量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时我会看到以十六进制定义的Integer常量,而不是十进制数字。这是我从GL10类中取得的一小部分:

  public static final int GL_STACK_UNDERFLOW = 0x0504; 
public static final int GL_OUT_OF_MEMORY = 0x0505;
public static final int GL_EXP = 0x0800;
public static final int GL_EXP2 = 0x0801;
public static final int GL_FOG_DENSITY = 0x0B62;
public static final int GL_FOG_START = 0x0B63;
public static final int GL_FOG_END = 0x0B64;
public static final int GL_FOG_MODE = 0x0B65;

定义 2914 而不是 0x0B62 ,那么可能会有一些性能增益?我真的不这么认为,因为那时它应该是编译器的工作来改变它。 解决方案

和视觉清洁度。基数16与二进制数的关系比基数10要简单得多,因为在基数16中,每个数字对应于正好四位。

注意在上面的常量是如何分组的与许多数字相同。如果它们用十进制表示,通常的位不太清楚。如果它们有相同的十进制数字,则位模式不会有相同程度的相似性。

另外,在许多情况下,希望能够按位或常量一起创建标志的组合。如果每个常数的值被限制为仅具有非零位的子集,则可以以可以重新分离的方式完成这一点。使用十六进制常量可以清除每个值中的哪些位不为零。

还有其他两种合理的可能性:八进制或8进制简单编码每位数3位。然后是二进制编码的十进制,其中每个数字需要四位,但是高于9的数字值被禁止 - 这将是不利的,因为它不能表示二进制可能的所有可能性。


Sometimes I see Integer constants defined in hexadecimal, instead of decimal numbers. This is a small part I took from a GL10 class:

public static final int GL_STACK_UNDERFLOW = 0x0504;
public static final int GL_OUT_OF_MEMORY = 0x0505;
public static final int GL_EXP = 0x0800;
public static final int GL_EXP2 = 0x0801;
public static final int GL_FOG_DENSITY = 0x0B62;
public static final int GL_FOG_START = 0x0B63;
public static final int GL_FOG_END = 0x0B64;
public static final int GL_FOG_MODE = 0x0B65;

It's obviously simpler to define 2914 instead of 0x0B62, so is there maybe some performance gain? I acutallly don't think so, since then it should be the compiler's job to change it.

解决方案

It is likely for organizational and visual cleanliness. Base 16 has a much simpler relationship to binary than base 10, because in base 16 each digit corresponds to exactly four bits.

Notice how in the above, the constants are grouped with many digits in common. If they were represented in decimal, bits in common would be less clear. If they instead had decimal digits in common, the bit patterns would not have the same degree of similarity.

Also, in many situations it is desired to be able to bitwise-OR constants together to create a combination of flags. If the value of each constant is constrained to only have a subset of the bits non-zero, then this can be done in a way that can be re-separated. Using hex constants makes it clear which bits are non-zero in each value.

There are two other reasonable possibilities: octal, or base 8 simply encodes 3 bits per digit. And then there is binary coded decimal, in which each digit requires four bits, but digit values above 9 are prohibited - that would be disadvantageous as it cannot represent all of the possibilities which binary can.

这篇关于为什么使用十六进制常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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