我正试图从byteData
读取几个字节,如下文C ++代码所述。 byteData
中的实际值是BIG-ENDIAN字节顺序格式的二进制Blob字节数组。因此,我不能简单地将字节数组“转换”为字符串。byteData
字节数组由这三件事组成-
First is `schemaId` which is of two bytes (short datatype in Java)
Second is `lastModifiedDate` which is of eight bytes (long datatype in Java)
Third is the length of actual `byteArray` within `byteData` which we need from `byteData`.
Fourth is the actual value of that `byteArray` in `byteData`.
现在,我正在尝试从C ++中的
byteData
中提取上述特定信息...以某种方式我可以提取schemaId
,而我得到的值也正确。.现在,我不确定如何提取其他值事情...uint16_t schemaId;
uint64_t lastModifiedDate;
uint16_t attributeLength; // or it should be uint32_t?
const char* actual_binary_value;
while (result.next()) {
for (size_t i = 0; i < result.column_count(); ++i) {
cql::cql_byte_t* byteData = NULL;
cql::cql_int_t size = 0;
result.get_data(i, &byteData, size);
// I cannot just "cast" the byte array into a String
// value = reinterpret_cast<char*>(byteData);
// this works fine
schemaId = ntohs(*reinterpret_cast<uint16_t*>(byteData));
// now how to retrieve lastModifiedDate, length of binary value and actual_binary_value from byteData?
// the below doesn't works..
lastModifiedDate = be64toh(*reinterpret_cast<uint64_t*>(data));
// And how to extract other things as well?
}
// this prints out `9223090561897746107` but it should print out `1289811105109`
cout<< lastModifiedDate <<endl;
// And print out other things..
}
如果有人需要查看我的Java代码,那么这就是我的Java代码-
byte[] avroBinaryValue = text.getBytes();
long lastModifiedDate = 1289811105109L;
short schemaId = 32767;
int size = 2 + 8 + 4 + avroBinaryValue.length; // short is 2 bytes, long 8 and int 4
ByteBuffer bbuf = ByteBuffer.allocate(size);
bbuf.order(ByteOrder.BIG_ENDIAN);
bbuf.putShort(schemaId);
bbuf.putLong(lastModifiedDate);
bbuf.putInt(avroBinaryValue.length);
bbuf.put(avroBinaryValue);
// merge everything into one bytearray.
byte[] bytesToStore = bbuf.array();
Hex.encodeHexString(bytesToStore)
谁能帮我在C ++代码中做错什么,为什么我不能从它和其他字段中正确提取
lastModifiedDate
?据我了解,lastModifiedDate
是64位整数,那么这里有什么方法可以换出64位整数?还是其他更好的转换方法?简而言之,我正在尝试从C ++中的字节数组中提取
schemaId
,lastModifiedDate
,avroBinaryValue.length
和avroBinaryValue
。我可以提取
schemaId
,但现在我被其他事情困扰了... 最佳答案
您的方法看起来不错,我只看到两个可能的问题。
所示的代码只是将未定义的变量data
强制转换为uint64_t
。确保您确实在前进数据缓冲区并转换正确的数据。
平台依赖性。据我了解,并不是所有平台都普遍支持64位字节交换功能(be64toh,betoh64,ntohll等)。您可能需要在平台上使用其他功能,并且/或者如果您希望代码独立于平台,则可以自动检测哪些功能有效。例如,请参见类似的问题here和here。
关于如何获取数据,类似这样的方法应该起作用:
int index=0;
schemaId = ntohs(*reinterpret_cast<uint16_t*>(&byteData[index]));
index += 2;
lastModifiedDate = be64toh(*reinterpret_cast<uint64_t*>(&byteData[index]));
index += 8;
attributeLength = ntohl(*reinterpret_cast<uint32_t*>(&byteData[index]));
index += 4;
actual_binary_data = (const char *)&byteData[index];