[英]How to extract individual fields from byte array (which is in BIG-ENDIAN) in C++
我特林讀取幾個字節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;
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);
if (!flag) {
// I cannot just "cast" the byte array into a String
// value = reinterpret_cast<char*>(byteData);
// now how to retrieve schemaId, lastModifiedDate and actual_binary_value from byteData?
schemaId = *reinterpret_cast<uint16_t*>(byteData);
flag = false;
}
}
// this prints out 65407 somehow but it should be printing out 32767
cout<< schemaId <<endl;
}
如果有人需要查看我的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 ++代碼中做錯了什么以及為什么我無法從它和其他領域正確提取schemaId?
更新: -
用完之后 -
schemaId = ntohs(*reinterpret_cast<uint16_t*>(data));
我開始正確地為schemaId獲取值。
但現在如何提取其他的東西,如lastModifiedDate
,實際的長度byteArray within
byteData and actual value of that
的ByteArray in
byteData`。
我正在將它用於lastModifiedDate
但它不能以某種方式工作 -
std::copy(reinterpret_cast<uint8_t*>(byteData + 2), reinterpret_cast<uint8_t*>(byteData + 10), lastModifiedDate);
32767是0x7fff。 65407是0xff7f。 請注意,交換高階和低階字節。 您需要交換這些字節以將數字恢復為原始值。 幸運的是,有一個名為ntohs
(網絡到主機短路)的宏或函數可以完全滿足您的需求。 這是宏還是函數,以及定義的頭,取決於您的系統。 但是,無論是使用Windows,Linux,Sun還是Mac,宏/函數的名稱總是ntohs
。
在小端機器上,此宏或函數交換形成16位整數的兩個字節。 在大端機器上,這個宏/函數什么都不做(這正是所需的)。 請注意,現在大多數家用電腦都是小端。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.