java - 在定义int类型的变量时,使用十六进制表示有什么好处?
PHP中文网
PHP中文网 2017-04-17 13:54:33
0
3
1411

最近我在看android源码的时候,发现它里面有很多static final int类型的常量都是使用十六进制来表示的:

所以我想问一下,在代码里,使用十六进制和十进制来表示整数有什么区别?或者说,相对十进制,使用十六进制来表示整数有什么好处?

另外,我还发现,在定义常量的时候,他们并不是随便的拿一个十六进制数来赋值的,它取的值里面一般都会包含1、2、4、8这几个数字,这里面又有什么巧妙之处?

PHP中文网
PHP中文网

认证0级讲师

reply all(3)
伊谢尔伦

There are several benefits of using hexadecimal, such as:

  1. It is easy to see the common characteristics of corresponding positions. For example, the first three digits of MODE_WORLD_READABLE and MODE_WORLD_WRITABLE in your screenshot are 0 (hexadecimal). If you use decimal numbers, this representation is not obvious

  2. Using hexadecimal (which can quickly correspond to binary one-to-one), it is convenient to perform bit mask operations, such as shifting, or OR to calculate a combined identification flag.

stackoverflow portal: http://stackoverflow.com/questions/10920432/why-use-hexadecimal-consta...

巴扎黑

My personal guess is to make bit operations more intuitive. A lot of bit operations are used in the Android source code. Compared with the decimal system, the hexadecimal system is more intuitive and easy to understand.

Ty80

Take ViewGroup source code as an example:

    static final int FLAG_CLIP_CHILDREN = 0x1;
    private static final int FLAG_CLIP_TO_PADDING = 0x2;
    static final int FLAG_INVALIDATE_REQUIRED  = 0x4;
    private static final int FLAG_RUN_ANIMATION = 0x8;
    static final int FLAG_ANIMATION_DONE = 0x10;
    private static final int FLAG_PADDING_NOT_NULL = 0x20;
    private static final int FLAG_ANIMATION_CACHE = 0x40;
    static final int FLAG_OPTIMIZE_INVALIDATE = 0x80;
    static final int FLAG_CLEAR_TRANSFORMATION = 0x100;

Then all the above attributes are marked together with an int variable mGroupFlags, and each bit records the status of an attribute (0 or 1)

Using hexadecimal is more intuitive and you can calculate it mentally directly

第0位表示FLAG_CLIP_CHILDREN
第1位表示FLAG_CLIP_TO_PADDING
第2位表示FLAG_INVALIDATE_REQUIRED
第3位表示FLAG_RUN_ANIMATION
第4位表示FLAG_ANIMATION_DONE
....
....

If it is written in decimal, it will be more troublesome to calculate which digit represents which variable, and it looks very painful

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!