Ich bin neu in Python. In Perl, um bestimmte Bits auf eine skalare Variable (Ganzzahl) zu setzen, kann ich vec()
wie unten verwenden.Python entspricht perl vec() Funktion
#!/usr/bin/perl -w
$vec = '';
vec($vec, 3, 4) = 1; # bits 0 to 3
vec($vec, 7, 4) = 10; # bits 4 to 7
vec($vec, 11, 4) = 3; # bits 8 to 11
vec($vec, 15, 4) = 15; # bits 12 to 15
print("vec() Has a created a string of nybbles,
in hex: ", unpack("h*", $vec), "\n");
Ausgang:
vec() Has a created a string of nybbles,
in hex: 0001000a0003000f
Ich frage mich, wie man das gleiche in Python zu erreichen, ohne Bit-Manipulations Code zu schreiben und struct.pack manuell mit?
Wenn Sie Bit-Manipulations Code sagen, meinen Sie Bitshift << >>? – user2958652
Sie sagen, es setzt die Bits 0 bis 3, 4 bis 7 usw., aber es setzt Nibbles 3 (Bits 12 bis 15), 7 (Bits 28 bis 31) usw. Es sollte einfach sein, Ihre eigenen 'Vec zu schreiben 'wenn es kein Äquivalent gibt. – ikegami
Vielleicht würde die Frage [Bit-Array in Python] (http://stackoverflow.com/q/11669178/2157640) helfen. – Palec