/*2022-8-19学习9-QT界面开发03目录代码
*字节数组:插入1 讲数据如何放入数组中
* 访问2 数据如何访问
* 删除3
* 替换4
* 重复5
* 大小6
* 转换7
*/
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include<QVector>
#include<QDebug>
#include<QByteArray>
using namespace std;
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
QByteArray bytes;//字节数组
int size_l=bytes.size();
int capacity_l= bytes.capacity();
//bytes.resize(10);//如果预先知道需要的空间大小可以提前扩容,避免多次分配
//扩充寻找更大的一片内存空间,其地址可以会改变
//自适应:分配size空间(垃圾数据) 和更大的 容量capacity
//size变大会自动填充数据,变小会删除多余数据
//bytes.squeeze();//容量和实际大小 相同 很少用
//bytes.reserve();//只会分配更大的容量,不会主动改变size大小,
//一旦设置大容量在设置小容量 不会改变
//bytes.truncate(2);//保留截取的部分[0,2)比如0123 会变成01
//bytes.append(1);
//bytes.append(3);
bytes[0]='0';
bytes[1]='1';
bytes[2]='2';
bool ok(false);
//quint32 x1= bytes.toInt(&ok,0);//一参:返回是否成功 二参:自适应转换
std::string s1=bytes.toStdString();//字节数组 转 字符串
//转换成标准c++ 字符串做更多的操作
//QT更侧重UI布置
std::string s2("buit");//字符串 转 字节数组
QByteArray byte2=QByteArray::fromStdString(s2);
QByteArray byte3=bytes.toHex();//转成16进制
//先将目标转换成对应的16进制字符再储存下来
QByteArray h1=QByteArray::fromHex(byte3);//转成16进制转字节数组
qDebug()<<h1<<ok;
//类型转换
#if 0
QByteArray re=bytes.repeated(2);//以原有数据x2载入新空间
#endif
#if 0
//第一参数为索引 第二参数为替换长度(如果替换数据长就扩充空间)
bytes.replace(1,2,"ssss");//索引为1 长度为2 替换ssss空间不足的扩充
bytes.replace(1,2,"aaaaaaa",3);//索引为1 长度为2 替换aaa空间不足的扩充
#endif
#if 0
//bytes{1 2 3 4 5}
bytes.remove(2,1);//1 2 4 5
bytes.remove(1,2);//1 5 从下标多少开始删, 删除长度为多少
#endif
#if 0
for(auto x:bytes)
qDebug()<<(int)x;//使用数据转换类型
#endif
#if 0
for(QByteArray::Iterator it=bytes.begin();
it!=bytes.end();it++)
{
qDebug()<<(int)*it;
}
#endif
#if 0
qDebug()<< bytes[1]//1-QByteRef ref=bytes.operator[](0)
//2-char c=(char)ref; 得到
#endif
#if 0
char x[4]={1,2,3,4};
QByteArray byte2=QByteArray::fromRawData(x,3);
const char* data1=byte2.constData();//会指向原数据地址
char* data2=byte2.data();//会单独拷贝一份
#endif
#if 0
//data()将原始数据拷贝一份 以\0结尾
char date1=bytes.data();
for(int i=0;i<bytes.size();i++)
{
qDebug()<<(int)data1[i];
}
//二者的区别
const char* data=bytes.constData();
for(int i=0;i<bytes.size();i++)
{
qDebug()<<(int)data[i];
//qDebug()<<data[i];
}
#endif
#if 0
bytes[0]=0;
bytes[1]=1;
bytes[2]=2;
bytes.insert(3,0x16);
bytes.insert(4,' ');
//[5-7]初始化' '空 0x20
bytes.insert(8,0x30);//直接开辟到size 8
#endif
#if 0
//[]赋值
//索引存在(0,size())修改现有元素 索引存在(size(),..)增加新元素
bytes[0]=1;
bytes[1]=1;
//[2,4]未初始化垃圾数据
bytes[5]=5;//直接开辟到size 5
#endif
#if 0
bytes.append(1);
bytes.append(2);//在数组末尾插入 尾插
#endif
return app.exec();
}
QT字节数组篇:相关基础函数学习
最新推荐文章于 2024-09-04 08:26:51 发布