Create a MIPS program that takes an ASCII string of hexadecimal digits inputted by the user and converts it into an integer.
# $a0 - input, pointer to null-terminated hex string
# $v0 - output, integer form of binary string
# $t0 - address of start of lookup table
# $t1 - ascii value of the char pointed to
# $t2 - address of the integer value for the char in lookup
table
# $t3 - integer value of hex char (0 - 15)
hex_convert:
li $v0,
0
# Reset accumulator to 0.
la $t0,
hexvals
# Load address of lookup into register.
loop:
lb $t1,
0($a0)
# Load a character,
beq $t1, $zero,
end # if it is null
then return.
sll $v0, $v0,
4
# Otherwise first shift accumulator by 4 to multiply by 16.
addi $t2, $t1,
-48 #
Then find the offset of the char from '0'
sll $t2, $t2,
2
# in bytes,
addu $t2, $t2,
$t0 #
use it to calcute address in lookup,
lw $t3,
0($t2)
# retrieve its integer value,
addu $v0, $v0,
$t3 #
and add that to the accumulator.
addi $a0, $a0,
1
# Finally, increment the pointer
j
loop
# and loop.
end:
jr $ra
.data
IN PYTHON 3 , THE PROGRAM IS AS FOLLOWS ;-
def hexadecimalToDecimal(hexval):
# Finding length
length = len(hexval)
# Initialize base value to 1,
# i.e. 16*0
base = 1
dec_val = 0
# Extracting characters as digits
# from last character
for i in range(length - 1, -1, -1):
# If character lies in
'0'-'9',
# converting it to
integral 0-9
# by subtracting 48 from
ASCII value
if hexval[i] >= '0'
and hexval[i] <= '9':
dec_val += (ord(hexval[i]) - 48) * base
# Incrementing base by power
base = base * 16
# If character lies in
'A'-'F',converting
# it to integral 10-15
by subtracting 55
# from ASCII value
elif hexval[i] >= 'A'
and hexval[i] <= 'F':
dec_val += (ord(hexval[i]) - 55) * base
# Incrementing base by power
base = base * 16
return dec_val
# Driver code
if __name__ == '__main__':
hexnum = '1A'
print(hexadecimalToDecimal(hexnum))
If the hexadecimal number is 1A.
dec_value = 1*(16^1) + 10*(16^0) = 26
Get Answers For Free
Most questions answered within 1 hours.