先来看一个错误:
125 | if (get_uint32_from_tlv_chain(pTlvList, 31, &dwBaseScore) < 0) { LOG_BUG_RET(-1); } |
126 | if (get_uint32_from_tlv_chain(pTlvList, 6, &dwBestAnsUid1) < 0) { dwBestAnsUid1 = 0; } |
127 | if (get_uint32_from_tlv_chain(pTlvList, 7, &dwBestAnsUid2) < 0) { dwBestAnsUid2 = 0; } |
128 | if (get_uint32_from_tlv_chain(pTlvList, 8, &dwReason) < 0) { dwReason = 0; } |
129 | fBaseScore = *(float *)(&dwBaseScore); |
一般来说在通信协议中传输浮点数的需求不多,也尽量避免。如果有,那怎么办?这里提供一个做法。
static void writeDouble(PyObject* outbuf, double dub) {
// Unfortunately, bitwise_cast doesn't work in C. Bad C!
union {
double f;
int64_t t;
} transfer;
transfer.f = dub;
writeI64(outbuf, transfer.t);
}
static double readDouble(DecodeBuffer* input) {
union {
int64_t f;
double t;
} transfer;
transfer.f = readI64(input);
if (transfer.f == -1) {
return -1;
}
return transfer.t;
}
这是摘自thrift binary protocol的一段代码,这里使用的技巧很容易看明白。
对于float的也可以这么做。