2015-02-09 109 views
1

1)我使用十六進制值操作時遇到了一些問題。爲什麼sendValue(hex(12289))導致錯誤(中止腳本),而sendValue(0x3001)的作品?使用十六進制值操作時不能使用十六進制功能

def sendValue(value): 
    for i in range(16): 
     if (value & 0x8000): 
      print "1" # later this bit will be sent to a LC 
     else: 
      print "0" # later this bit will be sent to a LC 
     value <<= 1 # corrected this 

def main(): 
    sendValue(0x3001) 
    sendValue(hex(12289)) 

if __name__ == '__main__': 
    main() 

2)我所期望的輸出

0 
0 
1 
1 
0 
0 
0 
0 
0 
0 
0 
0 
0 
0 
0 
1 

但我只是得到0

+2

**什麼**錯誤? – 2015-02-09 08:53:11

+2

這是因爲'hex(12289)'返回一個'string',並且你將它與'if'中的'number'進行比較。所以它會拋出一個錯誤。 – 2015-02-09 08:58:58

+2

你不要在循環中的任何地方使用'i'。你正在做'價值&0x8000' 16次。 – 2015-02-09 09:02:25

回答

2

sendValue()功能只是打印數量16倍的最顯著位。您需要掃描每個位。例如,

#!/usr/bin/env python 

def sendValue(value): 
    print hex(value), 

    for i in range(16): 
     if (value & 0x8000): 
      print "1", 
     else: 
      print "0", 

     #Right-shift value to put next bit into the MSB position 
     value <<= 1 

    print 


def main(): 
    sendValue(0x3001) 
    sendValue(12289) 
    sendValue(0x123f) 


if __name__ == '__main__': 
    main() 

**output** 

0x3001 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 1 
0x3001 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 1 
0x123f 0 0 0 1 0 0 1 0 0 0 1 1 1 1 1 1 

注意,Python有一個內置的bin()函數整數轉換爲位串:

>>> bin(0x3001) 
'0b11000000000001' 
>>> bin(0xfed) 
'0b111111101101' 

但是,如果你不想使用bin()由於某些原因,還有其他這種方法比我以前的代碼更加簡潔。例如,將value移至左側並用& 1將其掩蓋,如下所示:

def sendValue(value): 
    print hex(value), 
    print ' '.join([str(value >> i & 1) for i in range(16, -1, -1)]) 
2

你得到這個錯誤,因爲hex函數返回的字符串。十六進制,二進制,十進制只是整數值的表示。 12289和0x3001是一樣的,所以,你可以這樣做:

def main(): 
    sendValue(0x3001) 
    sendValue(12289) 

    # Or convert string to int if you need 
    sendValue(int(hex(12289), 16))