sto cercando di tradurre il seguente codice Python in C++:disimballaggio carri hex-encoded
import struct
import binascii
inputstring = ("0000003F" "0000803F" "AD10753F" "00000080")
num_vals = 4
for i in range(num_vals):
rawhex = inputstring[i*8:(i*8)+8]
# <f for little endian float
val = struct.unpack("<f", binascii.unhexlify(rawhex))[0]
print val
# Output:
# 0.5
# 1.0
# 0.957285702229
# -0.0
Così si legge a 32 bit nel valore della stringa esadecimale con codifica, lo trasforma in un byte-array con il metodo unhexlify
e lo interpreta come valore float little-endian.
Di seguito quasi funziona, ma il codice è una specie di scadente (e l'ultimo 00000080
analizza in modo errato):
#include <sstream>
#include <iostream>
int main()
{
// The hex-encoded string, and number of values are loaded from a file.
// The num_vals might be wrong, so some basic error checking is needed.
std::string inputstring = "0000003F" "0000803F" "AD10753F" "00000080";
int num_vals = 4;
std::istringstream ss(inputstring);
for(unsigned int i = 0; i < num_vals; ++i)
{
char rawhex[8];
// The ifdef is wrong. It is not the way to detect endianness (it's
// always defined)
#ifdef BIG_ENDIAN
rawhex[6] = ss.get();
rawhex[7] = ss.get();
rawhex[4] = ss.get();
rawhex[5] = ss.get();
rawhex[2] = ss.get();
rawhex[3] = ss.get();
rawhex[0] = ss.get();
rawhex[1] = ss.get();
#else
rawhex[0] = ss.get();
rawhex[1] = ss.get();
rawhex[2] = ss.get();
rawhex[3] = ss.get();
rawhex[4] = ss.get();
rawhex[5] = ss.get();
rawhex[6] = ss.get();
rawhex[7] = ss.get();
#endif
if(ss.good())
{
std::stringstream convert;
convert << std::hex << rawhex;
int32_t val;
convert >> val;
std::cerr << (*(float*)(&val)) << "\n";
}
else
{
std::ostringstream os;
os << "Not enough values in LUT data. Found " << i;
os << ". Expected " << num_vals;
std::cerr << os.str() << std::endl;
throw std::exception();
}
}
}
(compila su OS X 10.7/gcc-4.2.1, con un semplice g++ blah.cpp
)
In particolare, mi piacerebbe sbarazzarmi delle macro macro BIG_ENDIAN
, in quanto sono sicuro che c'è un modo più bello per farlo, come discute lo this post.
Pochi altri dettagli casuali - Non riesco a utilizzare Boost (dipendenza troppo grande per il progetto). La stringa di solito contengono tra 1536 (8 * 3) e 98304 valori float (32 * 3), al massimo 786.432 (64 * 3)
(EDIT2: aggiunto un altro valore, 00000080
== -0.0
)
Penso che si intende (c - 'A') + 10; supponendo che sarà solo maiuscolo A –
Inoltre, il vantaggio di farlo da solo cifra per cifra è che puoi eseguire il ciclo da sinistra a destra o da destra a sinistra a seconda della endianità –
@OrgnlDave - ecco perché 'tolower' c'è. Sì sulla endianità, anche se diventa leggermente più complicato (per le cifre a byte singolo non si scambiano) –