I'm not sure what I'm doing wrong, but my print statement doesn't seem to be working.
def nib(string):
if string == '0000':
return '0'
if string == '0001':
return '1'
if string == '0010':
return '2'
if string == '0011':
return '3'
if string == '0100':
return '4'
if string == '0101':
return '5'
if string == '0110':
return '6'
if string == '0111':
return '7'
if string == '1000':
return '8'
if string == '1001':
return '9'
if string == '1010':
return "A"
if string == '1011':
return "B"
if string == '1100':
return "C"
if string == '1101':
return "D"
if string == '1110':
return "E"
if string == '1111':
return "F"
def main(nib):
strings= input("Enter your 4 bit binary nibble, separated by spaces: ")
strings= strings.split(' ')
print(string)
I'd like to maintain the code in the simple format I have since I'm a beginner. Here are my instructions:
Write a function that takes as an argument, a 4 bit binary nibble represented as a string, and returns its hex equivalent value as a String
Use that function to write a program that accepts an entire string of binary nibbles entered from the keyboard and prints out the full hex equivalent. The nibbles in the input must be separated by spaces.
For Example:
An input of 0101 1101 produces an output of 5D An input of 0000 1001 0001 1111 1100 produces an output of 091FC
I don't know where I went wrong?????
There are a few things wrong with your code:
Your code to accept the input values is correct. I suggest you rename your variables to something that makes sense. Also your
mainfunction doesn't need anibargument. Thenibfunction is already defined in the global scope. Also, you don't need to specify an argument to.splitif you want to split on spaces -- that is the default behavior.At this point, you have a list of input nibbles, and you need to convert each of them. Once you convert each of them, you need to join the individual hex digits to a single string.
Note: You can skip the need to define
hex_digitsand dohex_valuedirectly like so:hex_value = "".join(nib(s) for s in strings)Now, your
nibfunction works, but you could clean it up a little to be more terse. You could define a dictionary which maps the binary values to the hex digits, and use that instead of a bunch ofifstatements (remember to fill in all the key-value pairs inbin_to_hex.You could even define
bin_to_hexusing a loop:The
f"..."construct is called the f-string syntax.:bformats an integer as a binary string, and:04pads the result with zeros to a width of 4.:xformats an integer as a hex string. Doing this for all integers in therange(16)allows us to create thebin_to_hexwithout manually typing everything out.