将QByteArray从大端转换为小端 [英] Convert QByteArray from big endian to little endian

查看:2731
本文介绍了将QByteArray从大端转换为小端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我觉得我有点不知所措.我尝试了这么简单的事情,我不敢相信没有内置的Qt(使用Qt 5.6.2).我尝试将QByteArray中的数据从大端转换为小端.总是以相同的测试QByteArray开头.

I think I’m a kind of at a loss here. I trying such a simple thing, I can’t believe that there is nothing build-in Qt (using Qt 5.6.2). I try to convert the data inside a QByteArray from big endian to little endian. Always starts with the same test QByteArray like this.

QByteArray value;
value.append(0x01);
value.append(0x02);
value.append(0x03);
qDebug() << "Original value is: " << value.toHex(); // "010203" like expected

我需要的是小字节序,这意味着输出应为"030201".到目前为止,Qt Framework中是否有任何内置的东西?我找不到一个.到目前为止我尝试过的

What I need is the little endian, which means the output should be "030201". Is there any build in thing so far in the Qt Framework? I don’t find one. What I tried so far

// Try with build in QtEndian stuff
QByteArray test = qToLittleEndian(value);
qDebug() << "Test value is: " << test.toHex(); // 010203

// Try via QDataStream
QByteArray data;
QDataStream out(&data, QIODevice::ReadWrite);
out.setByteOrder(QDataStream::LittleEndian);
out << value;
qDebug() << "Changed value is: " << data.toHex(); // "03000000010203"

有什么好主意吗?还是我真的需要手动换手?在SO或Google上没有发现任何帮助,或者问了一个错误的问题...

Any good idea? Or do I really need to shift hands by hand? Found nothing helpfull on SO or on google or maybe ask the wrong question...

推荐答案

听起来您想反转数组,而不是操纵数组内任何多字节类型的字节序.标准库为此提供了一个解决方案:

It sounds like you want to reverse the array, rather than manipulate the endianness of any of the multi-byte types inside the array. The standard library has a solution for this:

QByteArray arr;
std::reverse(arr.begin(), arr.end());
// arr is now in reversed order

这篇关于将QByteArray从大端转换为小端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆