Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

pack per creare stringa binaria

1 view
Skip to first unread message

Larry

unread,
Dec 9, 2009, 7:02:43 AM12/9/09
to
[C++] Pack per creare una stringa binaria
Salve,

volevo sapere se in C++ esiste una funzione simile a Pack in Perl.

Nello specifico mi serviva per creare stringhe binarie composte da:

Key (lunghezza fissa 4 Bytes) + Lunghezza Value (lunghezza fissa 4 Bytes) +
Value

Quindi ad esempio:

KEY1....VALUE

Dove KEY1 � la chiave (4 Bytes) poi .... sono quello che qu� intendo come
non printable chars (4 Bytes) che descrivono la lunghezza di VALUE, infine
VALUE.

Cosi che possa creare una stringa binaria tipo:

KEY1....VALUEKEY2....VALUE etc...

in Perl avrei fatto qualcosa come:

codice:
my $key = 'KEY1';
my $value = "Hello World!";
my $value_len = length $value;
my $res = $key . pack("N", $value_len) . $value;


Dove la N di Pack sta per:


Citazione:

"N" - an unsigned long (32-bit) in "network" (big-endian) order.

?manu*

unread,
Dec 9, 2009, 8:48:53 AM12/9/09
to
Larry ha scritto:

> my $res = $key . pack("N", $value_len) . $value;

Se capisco bene cosa fa pack("N",...) puoi ottenerla cos�:

unsigned long int Endian_DWord_Conversion(unsigned long int dword) {
return ((dword>>24)&0x000000FF) | ((dword>>8)&0x0000FF00) |
((dword<<8)&0x00FF0000) | ((dword<<24)&0xFF000000);
}

std::string packN(unsigned long int dword) {
dword=Endian_DWord_Conversion(dword);
return std::string(reinterpret_cast<const char *>&dword,
sizeof(dword));
}

...codice non testato.

E.

0 new messages