我有用C ++编写的代码,我正在翻译成Python。 C ++代码是:
WriteBuffer[0] = unsigned char (0xc0 + (Steer & 0x1F)); // change the signal to conform to jrk motor controller
WriteBuffer[1] = unsigned char (Steer >> 5) & 0x7F; // two-word feedback signal
if(!WriteFile(hSerial[1], &WriteBuffer, 2, &BytesWritten, NULL)){
//error occurred. Report to user.
cout<<"error writing T2 \n";
cout<<BytesWritten;
}
我用Python编写的代码不起作用,是:
rightWheel = bytearray(b'\xc000')
rightWheel[0] = rightWheel[0] + (rightWheelSteer & 0x1F)
rightWheel[1] = (rightWheelSteer >> 5) & 0x7F
rightWheel = bytes(rightWheel)
ser2.write(rightWheel)
rightWheel的第一个字节似乎包含正确的数据,但第二个字节没有。我想rightWheel [1]包含一个字节,但它没有。
什么Python代码可以让我设置一个包含变量右移五位然后按位与0x7F的变量的字节?
答案 0 :(得分:1)
问题出在我的第一行代码中。我有这个:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="@android:color/holo_orange_light"
android:gravity="center"
android:text="item1"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="@android:color/holo_blue_light"
android:gravity="center"
android:text="item2"
/>
</LinearLayout>
但是这使得rightWheel成为3个字节,将最右边的两个0作为单字节ASCII字符,每个0。所以rightWheel成了b'\ xc0 \ x30 \ x30'。
此修改后的第一行代码正常工作:
rightWheel = bytearray(b'\xc000')