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

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

问题描述

有时我会看到以十六进制而不是十进制数定义的整数常量.这是我从 GL10 课程中摘取的一小部分:

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;

定义 2914 而不是 0x0B62 显然更简单,那么是否有一些性能提升?我完全不这么认为,从那时起,改变它应该是编译器的工作.

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.

推荐答案

它可能是为了组织和视觉清洁.与基数 10 相比,基数 16 与二进制的关系要简单得多,因为在基数 16 中,每个数字正好对应四位.

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.

还有另外两种合理的可能性:八进制或基数 8 简单地对每个数字 3 位进行编码.然后是二进制编码的十进制,其中每个数字需要四位,但禁止大于 9 的数字值 - 这将是不利的,因为它不能代表二进制可以的所有可能性.

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天全站免登陆