简体   繁体   中英

Python Code for Bin, Dec, Hex string Identifier & Converter

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.

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 ...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM