The last expression "0123456789abcdef" [0] is a common technique that can quickly convert a number to a hexadecimal character ." 0123456789abcdef "is a string literal, type: Char [17] (in C) or const char [17] (in C ++ ), the converted pointer types are char * and const char * respectively. Therefore, "0123456789abcdef" [0] is the first element '0 '. This technique is often used in hexadecimal conversion. The following code converts a memory image with a long integer to a hexadecimal representation:
Char * convert (unsigned long value)
{
Static char buffer [sizeof (unsigned long) * 2 + 1];
Int I;
For (I = sizeof (unsigned long) * 2-1; I> = 0; -- I)
{
Buffer [I] = "0123456789 abcdef" [Value % 16];
Value/= 16;
}
Return buffer;
}
Of course, I will introduce these odd expressions here to only discuss the subscript operators, rather than encouraging people to write such code. But in some cases, expressions like "0123456789 abcdef" [Value % 16] are still a good choice, compared with the following code:
Remainder = Value % 16;
If (remainder> = 10) buffer [I] = 'A' + remainder-10;
Else buffer [I] = '0' + remainder;
The former is obviously more concise, refined, and easier to read. Therefore, you should choose between different situations. Division and remainder operations are used in the Code. Some people prefer to replace these operations directly with shift operations to achieve high speed. However, modern compilers have already optimized the code very well. The efficiency difference between multiplication and division operations and direct shift is almost negligible, unless a large number of mathematical operations are required or extremely sensitive to efficiency, the improved speed will not compensate for the loss of readability. A balanced choice should be made between readability, space, and efficiency, rather than blindly pursuing extremes.
This article from the csdn blog, reproduced please indicate the source: http://blog.csdn.net/supermegaboy/archive/2009/11/23/4855000.aspx