有没有更短的方法来初始化QByteArray? [英] Is there a shorter way to initialize a QByteArray?

查看:1433
本文介绍了有没有更短的方法来初始化QByteArray?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的程序中,我经常进行串行通信,因此QByteArray经常使用.

In my program I work a lot with serial communication so QByteArray is used very often.

我想知道是否有比使用以下特定字节初始化QByteArray的短方法:

I was wondering if there was a shorter way to initialize a QByteArray with specific bytes than:

const char test_data[] = {
    static_cast<char>(0xB1), static_cast<char>(0xB2),
    0x5, static_cast<char>(0xFF),
    static_cast<char>(0xEE), static_cast<char>(0xEE),
    static_cast<char>(0x0)}; // Note QByteArray should be able to hold 0 byte
const QCanBusFrame frame = QCanBusFrame(0xA1, QByteArray(test_data));

static_cast<char>是必需的,因为否则C ++ 11会给出有关缩小的错误,因为0x7F到0xFF的范围大于char的范围,但是charQByteArray构造函数要求.

The static_cast<char> is necessary because otherwise C++11 gives an error about narrowing, because the range 0x7F to 0xFF is bigger than a char could fit--but a char is what the QByteArray constructor asks for.

这是正在使用的QByteArray构造函数:

This is the QByteArray constructor being used:

QByteArray::QByteArray(const char *data, int size = -1)

推荐答案

受到以上答案的启发,我终于想到了:

Being inspired by the answers above this is what I finally came up with:

const quint8 testData[] {0xB1, 0x00, 0xB2, 0x00};
const QCanBusFrame cFrame = QCanBusFrame(
    0xA1, QByteArray(reinterpret_cast<const char*>(testData), sizeof(testData)));

在进行串行通信时,我更喜欢将字节作为字节数而不是文字字符.

I much prefer to have the bytes as byte numbers rather than literal characters when working with serial communication.

在## c ++讨论之后,我被告知在这种情况下应适当使用reinterpret_cast.

After having a discussion on ##c++ I was advised that reinterpret_cast is appropriately used in this situation.

这篇关于有没有更短的方法来初始化QByteArray?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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