Pythonによる2進数変換と論理演算(or,xor)

2進数変換

def binBin(num1,num2):
    binNum1 = list(bin(num1))
    binNum1.pop(0)
    binNum1.pop(0)
    binNum2 = list(bin(num2))
    binNum2.pop(0)
    binNum2.pop(0)
 
    while(len(binNum1) != len(binNum2)):
        if len(binNum1) < len(binNum2):
            binNum1.insert(0,0) 
        elif len(binNum2) < len(binNum1):
            binNum1.insert(0,0) 
    return binNum1, binNum2

10進数変換

def binNum(binNum):
    Num = 0
    for i in range(len(binNum)):
 
        if int(binNum[len(binNum)-i-1]) == 1:
            Num += pow(2,i)
    return Num 

or計算

def orCal(num1,num2):
    binNum1, binNum2 = binBin(num1,num2)
    orValue = []
    for i in range(len(binNum1)):
        if int(binNum1[i]) == 1 or int(binNum2[i]) == 1:
            orValue.append(1)
        else:
            orValue.append(0)
    return binNum(orValue)

xor計算

def xorCal(num1,num2):
    binNum1, binNum2 = binBin(num1,num2)
    xorValue = []
    for i in range(len(binNum1)):
        if int(binNum1[i]) == int(binNum2[i]):
            xorValue.append(0)
        else:
            xorValue.append(1)
 
    return binNum(xorValue)

計算例

# orを計算
print(orCal(3,5))
# xorを計算
print(xorCal(3,5))
7
6
Tags: