[英]Python display the data array by left shifting the string data
我想通過左移str
數據來顯示數組數據。 我已經寫了代碼,它的工作部分。 代碼如下:
我期望在Python中實現輸出嗎?提供解決方案
response = '62 D9 57 00 00 25 27 00 00 28 77 00 02 4D 27 11 22 33 44'
data = response.split()
index = 3
for i in range(0,3):
TempMSBData = (data[index])
print '1st Byte:' + ' ' + TempMSBData
index = index + 1
MSBData = (data[index])
print '2nd Byte:' + ' ' + MSBData
index = index + 1
TempLSBData = (data[index])
print '3rd Byte:' + ' '+ TempLSBData
index = index + 1
LSBData = (data[index])
print '4th Byte:' + ' ' +LSBData
index = index + 1
DataResponse =(( int(TempMSBData) << 24)|( int(MSBData) << 16) | ( int(TempLSBData) <<8)| int(LSBData))
print 'Data_Ary_[{}] = {}'.format(i, DataResponse)
我收到以下Error
輸出
1st Byte: 00
2nd Byte: 00
3rd Byte: 25
4th Byte: 27
Data_Ary_[0] = 6427
1st Byte: 00
2nd Byte: 00
3rd Byte: 28
4th Byte: 77
Data_Ary_[1] = 7245
1st Byte: 00
2nd Byte: 02
3rd Byte: 4D
4th Byte: 27
Error is : DataResponse =(( int(TempMSBData) << 24)|( int(MSBData) << 16) | ( int(TempLSBData) <<8)| int(LSBData))
ValueError: invalid literal for int() with base 10: '4D'
我期望的輸出如下:
1st Byte: 00
2nd Byte: 00
3rd Byte: 25
4th Byte: 27
Data_Ary_[0] = 2527
1st Byte: 00
2nd Byte: 00
3rd Byte: 28
4th Byte: 77
Data_Ary_[1] = 2877
1st Byte: 00
2nd Byte: 02
3rd Byte: 4D
4th Byte: 27
Data_Ary_[2] = 024D27
1st Byte: 11
2nd Byte: 22
3rd Byte: 33
4th Byte: 44
Data_Ary_[3] = 11223344
如果我理解正確,則希望獲取一長串的十六進制部分並將它們分成4組,然后打印十六進制值。
您可以使用一個常見的python習慣用法使用zip()
來split()
zip()
:
for x in zip(*[iter(data)]*4):
x
將以4的塊為單位對數據進行迭代,例如第一次繞循環x = ('00', '00', '25', '27')
。 您可以解壓縮您的變量(但我不確定這會有所幫助):
for TempMSBData, MSBData, TempLSBData, LSBData in zip(*[iter(data)]*4):
如果您不需要數值,則可以在字符串中完成所有操作,而只需從0
s lstrip()
開始:
In [1]
response = '62 D9 57 00 00 25 27 00 00 28 77 00 02 4D 27 11 22 33 44'
data = response.split()[3:]
for x in zip(*[iter(data)]*4):
print(''.join(x).lstrip('0'))
Out[1]:
2527
2877
24D27
11223344
但是,如果希望將其數字化,則可以簡單地join
各部分連接起來並轉換為以int(n, 16)
底數的16。但是,在打印時,需要將format()
轉換為十六進制x
:
In [2]:
for x in zip(*[iter(data)]*4):
print(format(int(''.join(x), 16), 'x'))
Out[2]:
2527
2877
24d27
11223344
您得到的值是您看到的,因為您使用的是十進制打印:
In [3]:
for x in zip(*[iter(data)]*4):
print(format(int(''.join(x), 16), 'd'))
Out[3]:
9511
10359
150823
287454020
但是,您的計算不正確,您需要int(x, 16)
。
要通過數字方式完成所有操作,您可以執行以下操作:
In [4]:
for x in zip(*[iter(data)]*4):
i = 0
for n in x:
i <<= 8
i |= int(n, 16)
print(format(i, 'x'))
Out[4]:
2527
2877
24d27
11223344
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.