Reputation: 3025
Can someone explain why doing an OR operation on a binary number with 0x0030 as the operand produces the ASCII character of that number?
Upvotes: 1
Views: 30678
Reputation: 6018
Because looking at the ASCII chart, the digits 0 through nine start at 0x30. So you want the ASCII value for character 1? 0x30 or 0x01 = 0x31 = ASCII value for the number 1.
In binary it's easy to see:
(0x30) 110000
or
(0x01) 000001
= 110001
Which is 0x31 - ASCII value of 1.
Upvotes: 6
Reputation: 36630
Look at the binary representation of a single digit: e.g. 2d = 00000010b. Apply an OR-operation with 0x30 (00110000b) to it. This results in 00110010b which is 0x32 or 50d which is the ASCII-code for '2'. Effectively, in this case (since there are no carries to consider) the OR-operation is equal to adding 0x30.
Upvotes: 1
Reputation: 16553
If you're referring to numbers 0 through 9, the reason is that 0x30
(or 48) is the ASCII code of the number 0. Since 48 requires only bits in the higher (left hand) side of a byte, ORing it with any number below 16 (lower bits) is the same as mathematically adding the numbers.
So 0x30 OR 0x01 will give 0x31, the ASCII code of the character '1', and so on.
Upvotes: 2