0

I need Python code that takes a number input as a string and detects if it is binary, decimal or hexadecimal.

Also, I want to convert it to other two types without using bin(),dec(),hex(),int() commands.

2 Answers2

1
if my_num[0:2] == "0x" or my_num[0] == "x":print "hex"
elif my_num[0:2] == "0b" or my_num[0] == "b" and all(x in "01" for x in my_num):print "bin"
elif my_num[0] in "0O": print "oct"
elif re.match("^[0-9]+$",my_num): print "dec"
else: print "I dont know i guess its just a string ... or maybe base64"

is a way ...

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
0

This will tell you if an input string is bin, dec or hex

NOTE : As per steffano's comment, you will have to write something more to classify a number like 10 - which can be bin/dec/hex. Only one of the below functions should evaluate to true, otherwise you are wrong. Try to put this check.

import re

def isBinary(strNum):
    keyword = "^[0-1]*$"
    re.compile(keyword)
    if(re.match(keyword, strNum)) :
        return True
    else : 
        return False

def isDecimal(strNum):
    keyword = "^[0-9]*$"
    re.compile(keyword)
    if(re.match(keyword, strNum)) :
        return True
    else : 
        return False

def isHexa(strNum):
    keyword = "^[0-9a-fA-f]*$"
    re.compile(keyword)
    if(re.match(keyword, strNum)) :
        return True
    else : 
        return False
#Tests
print isHexa("AAD");
print isDecimal("11B")
print isBinary("0110a")

Output of this :

True
False
False
sudhishkr
  • 3,318
  • 5
  • 33
  • 55