Question

0xF, 0x0000000F (total width is 10 characters), and 0x0000000000000000F (total width is 18 characters) all mean 15 (decimal).

Is it correct to say that there is no reason to add leading zeros to a smaller hex number beyond 10 characters in total? In other words, is it correct to say that anything longer than the second version is excessive?

Was it helpful?

Solution

Hexadecimal numbers are typically used to represent binary data which have a fixed size in bytes. Hex numbers are prefixed with zeroes so the number of digits match the range.

So if you write a byte value as hex, you always write 2 hex digits, even if the number is below 16. You write 0A, not A or 00A even though they are technically the same number.

This is especially important when writing sequences of hex numbers. For example the two byte sequence 0A 0D could in theory be written as A D but then it would not be clear anymore that it is a two byte sequence. And if you write 000A 000D it would be interpreted as a 4-byte sequence which is quite different!

You use 4 hex digits to write a 16-bit value, 8 digits for a 32 bit value, 16 digits for a 64 bit value and so forth.

So there are contexts where you would use a large number of zeroes. Lets say you write the contents of a 64-bit register - writing 0x000000000000000F is entirely appropriate. It would be confusing if you left out some of the zeroes. (Although you would probably use spaces or separators to make it more readable like 0x0000 0000 0000 000F).

In contrast you would typically never add leading zeroes to a decimal number, since the leading zeroes does not carry any information. (Indeed, in some programming languages, a leading zero would cause a decimal number to be interpreted as an octal number.)

OTHER TIPS

The "appropriate" format is typically context dependent.

For example, if you're working in the context of a CPU with 64 bit registers, it might be more appropriate to write 0x0000 0000 0000 0003 instead of 0x3, just so that the register's width is communicated.

But in general, it's not much different than decimal numbers. If you have a $1,000 in your bank account, you wouldn't write $0,001,000 to be in the 6-zeros club

Licensed under: CC-BY-SA with attribution
scroll top