如何用C ++表示二进制字节数组?

时间:2013-10-15 09:15:48

标签: c++ bytearray endianness

我正在尝试使用libCQL library in C++从Cassandra检索数据....我在Cassandra中创建的表是这样的 -

create table test_cql (user_id text, column_name text, column_value blob, primary key (id, column_name));

以下是上表中的数据 -

cqlsh:testks> select column_name, column_value from test_cql where user_id = '1';

 column_name              | column_value
--------------------------+--------------------------------------------------------------------------------------------
 @hello.1381780131229.dc1 | 0x7fff0000012c4ebb95550000001e42797465204172726179205465737420466f722042696720456e6469616e

这里column_value是我想要检索的实际blob值......

下面是我所拥有的C ++代码,它将尝试从Cassandra中检索user_id = 1中的数据,其中我试图打印出column_name和column_value的详细信息。

    bool flag = false;
    std::map<std::string, std::string> m;
    std::string key, value;

    string query = "select column_name, column_value from test_cql where user_id ='1';";
    std::cout << query << endl;

// the below line will execute the query
    cql_result_t& result = execute_query(query);

// this will print out the result after executing the above query

    while (result.next()) {
        for (size_t i = 0; i < result.column_count(); ++i) {
            cql::cql_byte_t* data = NULL;
            cql::cql_int_t size = 0;
            result.get_data(i, &data, size);

            if (!flag) {
                key = reinterpret_cast<char*>(data);
                flag = true;
            } else if (flag) {
                value = reinterpret_cast<char*>(data);
                m[key] = value;
                flag = false;
            }
        }

        cout<<key << "-" << value <<endl;

    }

上面的代码只打印出键@hello.1381780131229.dc1但不是以某种方式输出值。它应该打印出值0x7fff0000012c4ebb95550000001e42797465204172726179205465737420466f722042696720456e6469616e,因为值是Cassandra表中的字节数组(二进制blob)是column_value。

我已经将键和值都声明为字符串,这可能是我在上面的代码中猜到的问题..但我相信值是Cassandra表中的实际blob(column_value)..所以我不知道如何检索使用上面的C ++代码的二进制blob(字节数组)?

此二进制字节数组blob值也可以是任何可变长度,并且始终以BIG-ENDIAN字节顺序格式存储。

来自Java背景,我有点问题......任何帮助都会受到赞赏...正如我猜的那样,它完全是C ++问题,比如我应该使用哪种数据类型来表示二进制字节数组。

1 个答案:

答案 0 :(得分:1)

因为二进制blob不是字符串,所以不能将其作为字符串打印。您必须手动打印“字符串”中的每个字节。

如果你想知道为什么,让我们看看前三个字节:0x7f0xff0x00。第一个字节和第二个字节都不可打印,第三个字节是字符串终止符,因此如果您将其打印为字符串,则打印将停止。

如果你有C ++ 11,你可以做类似

的事情
std::cout << "Value = 0x";
for (const char& byte : value)
    std::cout << std::hex << static_cast<int>(byte);
std::cout << std::endl;

还有一个问题是你试图将 它作为一个字符串,它不起作用(如上所述)。您可以使用std::string,但您必须使用构造函数:

value = str::string(reinterpret_cast<char*>(data), size);

如果数据实际上是一个结构,那么你可以使用它的结构:

struct employee
{
    uint16_t id;
    uint8_t lastModifiedDate[8];
    std::string value;
};

...

std::map<std::string, employee> m;

...

m[key].id = *reinterpret_cast<uint16_t*>(data);
std::copy(reinterpret_cast<uint8_t*>(data + 2),
          reinterpret_cast<uint8_t*>(data + 10),
          m[key].lastModifiedData);
m[key].value = std::string(reinterpret_cast<char*>(data + 10), size - 10);