How can I determine if the last digit of a decimal number is 1, given arbitrary numbers such as 21, 81, 35, 123, using only rudimentary bit operators?
My objective is to get more comfortable with bit operations such as xor
, and
as well as shifting.
The problem I'm facing is that some numbers will have the least significant bit set even though they do not end with the decimal digit one
, otherwise the last digit could be determined with a mask like this:
>>> '{0:08b}'.format( 5 & 1)
'00000001'
>>> '{0:08b}'.format( 500231 & 1)
'00000001'
Obviously, I'm a little confused, and would like some pointers on how to solve this problem. The example code is in Python, but suggestions and possible answers can be in any language including natural English.
What I have tried so far:
>>> def go():
... for i in [35,123,01,11,21,31,41,51,61,71,81,91,101]:
endswith1(i)
def endswith1(code):
# ...
# xxxxx
# & 00111
# ^ 00001
# 00000
filter = code & 7
isone = filter ^ 1
a = 'and 7: {0:08b}'.format( filter)
x = 'xor 1: {0:08b}'.format( isone )
b = '{0:08b}'.format( code)
one = isone == 0
print '%3d:%s %12s %12s %s' %( code,b, a,x, one)
#return ((code & 7) ^ 1 ) == 0
>>> go()
35:00100011 and 7: 00000011 xor 1: 00000010 False
123:01111011 and 7: 00000011 xor 1: 00000010 False
1:00000001 and 7: 00000001 xor 1: 00000000 True
11:00001011 and 7: 00000011 xor 1: 00000010 False
21:00010101 and 7: 00000101 xor 1: 00000100 False
31:00011111 and 7: 00000111 xor 1: 00000110 False
41:00101001 and 7: 00000001 xor 1: 00000000 True
51:00110011 and 7: 00000011 xor 1: 00000010 False
61:00111101 and 7: 00000101 xor 1: 00000100 False
71:01000111 and 7: 00000111 xor 1: 00000110 False
81:01010001 and 7: 00000001 xor 1: 00000000 True
91:01011011 and 7: 00000011 xor 1: 00000010 False
101:01100101 and 7: 00000101 xor 1: 00000100 False