I need some help converting:
- Binary - hex
- Binary decimal
- Hex - decimal
And vice versa using Python with no use of functions e.g binascii
I know a little Python, and I know a bit about arrays. Just can't get my head around this.
I need some help converting:
And vice versa using Python with no use of functions e.g binascii
I know a little Python, and I know a bit about arrays. Just can't get my head around this.
Well, there're built-in casting functions as bin or hex or int, I'm not sure how this will affect your "No use of functions". You can check the following code for them.
# Convert decimal to binary
>>> bin(10)
'0b1010'
>>> bin(10)[2:]
'1010'
>>> bin(10)[2:].zfill(8)
'00001010'
# Convert binary to decimal
>>> int('00001010',2)
10
# Convert decimal to hexadecimal
>>> hex(123)
'0x7b'
>>> hex(123)[2:]
'7b'
>>> hex(123)[2:].zfill(8)
'0000007b'
# Convert hexadecimal to decimal
>>> int('0000007b', 16)
123
# Convert binary to hexadecimal
>>> hex(int('1010', 2))
'0xa'
# Convert hexadecimal to binary
>>> bin(int('A', 16))
'0b1010'
Edit:
Sample algorithm ..
def dec2bin(num):
if num == 0: return '0'
bin_str = ''
while num > 0:
bin_str = str(num % 2) + bin_str
num = num / 2
return bin_str
Convrt string to int with base 2 and then to hex
>>> hex(int('010110', 2))
>>> '0x16'
>>> hex(int('0000010010001101', 2))
'0x48d'
Without functions:
101110101101
For example, to convert 101110101101 to hexadecimal, split it into fours:
1011 1010 1101
B A D
Now map each group to its Morse code..(as folows)
0000 0
0001 1
0010 2
0011 3
0100 4
0101 5
0110 6
0111 7
1000 8
1001 9
1010 A
1011 B
1100 C
1101 D
1110 E
1111 F