gpt4 book ai didi

c++ - 如何在 C++ 中从字节数组(BIG-ENDIAN)中提取单个字段

转载 作者:行者123 更新时间:2023-11-28 03:07:14 24 4
gpt4 key购买 nike

我想从 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`.

现在我试图从 byteData 中提取上述特定信息在 C++ 中...我能够以某种方式提取 schemaId但是即将到来的值(value)是错误的..而且我不确定如何从中提取其他东西......

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字节数据and actual value of that字节数组 in字节数据`。

我将其用于 lastModifiedDate但不知何故它不起作用——

std::copy(reinterpret_cast<uint8_t*>(byteData + 2), reinterpret_cast<uint8_t*>(byteData + 10), lastModifiedDate);

最佳答案

32767 是 0x7fff。 65407 是 0xff7f。请注意,交换了高位和低位字节。您需要交换这些字节以将数字恢复为原始值。幸运的是,有一个名为 ntohs(network to host short)的宏或函数可以完全满足您的需求。这是宏还是函数,以及定义在哪个 header 中,取决于您的系统。但是宏/函数的名称始终是 ntohs,无论是使用 Windows、Linux、Sun 还是 Mac。

在小端机器上,这个宏或函数交换构成 16 位整数的两个字节。在大端机器上,这个宏/函数什么也不做(这正是我们想要的)。请注意,现在大多数家用电脑都是小端。

关于c++ - 如何在 C++ 中从字节数组(BIG-ENDIAN)中提取单个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19392004/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com