Thread pack/unpack Daten von Socket (27 answers)
Opened by monti at 2012-11-22 19:47

FIFO
 2012-11-22 21:36
#163533 #163533
User since
2005-06-01
469 Artikel
BenutzerIn

user image
2012-11-22T18:47:17 monti
Code: (dl )
my $test=unpack "C11",$data;


Ich blicke gerade nicht durch wie ich die paar Bytes zu verwertbaren Zeichen verwandelt bekomme.


unpack() entpackt in Deinem Beispiel die ersten 11 Bytes von $data als unsigned char, das Ziel ist allerdings ein Array:

Code (perl): (dl )
my @octets = unpack("C11", $data);


Die octets kannst Du dann weiterverarbeiten. Z.B. als ASCII-Zeichen gedeutet:

Code (perl): (dl )
1
2
3
my $s = pack("C11", (65..75)); 
my @test = unpack("C11", $s);
print join(' : ', map {chr()} @test);


Ausgabe:
Code: (dl )
A : B : C : D : E : F : G : H : I : J : K


Editiert von FIFO: my ergänzt

edit: Wenn Du schon weißt, dass ASCII-Zeichen übertragen werden, kannst Du natürlich das unpack() direkt entsprechend gestalten:

Code (perl): (dl )
1
2
3
4
5
my $packet_length = 11;
my $unpack_str = 'A' x $packet_length;
my $s = pack("C11", (65..75));

print join(' : ', unpack($unpack_str, $s));


edit2: Wenn die 11 Bytes sicher ein ASCII-String sind (Byte-Reihenfolge?), kannst Du natürlich gleich in einen ASCII-String (Skalar) entpacken:

Code (perl): (dl )
1
2
my $data = pack("C11", (65..75));
my $str = unpack("A11", $data);

Last edited: 2012-11-23 09:39:16 +0100 (CET)
Everyone knows that debugging is twice as hard as writing a program in the first place. So if you're as clever as you can be when you write it, how will you ever debug it? -- Brian Kernighan: "The Elements of Programming Style"

View full thread pack/unpack Daten von Socket