7

无论我使用哪个 C 兼容库,当我查看标头定义的常量时,它们总是定义为十六进制值。例如,在 GL/gl.h 中:

#define GL_POINTS                               0x0000
#define GL_LINES                                0x0001
#define GL_LINE_LOOP                            0x0002
#define GL_LINE_STRIP                           0x0003
#define GL_TRIANGLES                            0x0004
#define GL_TRIANGLE_STRIP                       0x0005
#define GL_TRIANGLE_FAN                         0x0006
#define GL_QUADS                                0x0007
#define GL_QUAD_STRIP                           0x0008
#define GL_POLYGON                              0x0009

这种约定有什么特别的原因吗,为什么不简单地使用十进制值呢?

4

3 回答 3

7

有多种可能的原因:

1) 位标志更容易用十六进制表示,因为每个十六进制数字正好代表 4 位。

2)即使对于不是明确位标志的值,也经常有故意的位模式,当写成十六进制时更明显。

例如,所有的 AlphaFunction 都以 0x02 开头,并且只有一个字节不同:

#define GL_NEVER                          0x0200
#define GL_LESS                           0x0201
#define GL_EQUAL                          0x0202
#define GL_LEQUAL                         0x0203
#define GL_GREATER                        0x0204
#define GL_NOTEQUAL                       0x0205
#define GL_GEQUAL                         0x0206
#define GL_ALWAYS                         0x0207

3)十六进制值允许有前导零,因此更容易排列值。这可以使阅读(和校对)更容易。您可能会惊讶于十六进制和八进制文字中允许使用前导零,但十进制不允许使用前导零,但C++ 规范非常明确地表示

十进制整数文字(以十为基数)以 0 以外的数字开头,由一系列十进制数字组成。

于 2012-07-13T22:45:04.733 回答
2

如果常量值指的是位标志,并且打算组合,那么十六进制表示法是一种方便的方式来显示哪些位被表示。

例如,来自 Boost 标头:

// Type encoding:
//
// bit 0: callable builtin
// bit 1: non member
// bit 2: naked function
// bit 3: pointer
// bit 4: reference
// bit 5: member pointer
// bit 6: member function pointer
// bit 7: member object pointer

#define BOOST_FT_type_mask                            0x000000ff // 1111 1111 
#define BOOST_FT_callable_builtin                     0x00000001 // 0000 0001
#define BOOST_FT_non_member                           0x00000002 // 0000 0010
#define BOOST_FT_function                             0x00000007 // 0000 0111
#define BOOST_FT_pointer                              0x0000000b // 0000 1011
#define BOOST_FT_reference                            0x00000013 // 0001 0011
#define BOOST_FT_non_member_callable_builtin          0x00000003 // 0000 0011
#define BOOST_FT_member_pointer                       0x00000020 // 0010 0000
#define BOOST_FT_member_function_pointer              0x00000061 // 0110 0001
#define BOOST_FT_member_object_pointer                0x000000a3 // 1010 0001
于 2012-07-13T22:25:47.370 回答
0

它更短,但更重要的是,如果它们是位标志,则更容易将它们组合并制作掩码。

于 2012-07-13T22:26:37.683 回答