今天遇到一个问题,想要实现一种功能:在QLineEdit中书写16进制字符串比如 00 01 ff,然后保存为16进制转换后的字节形式到内存中,然后在文件中进行查找字符串匹配,后来发现QByteArray QByteArray::fromHex(const QByteArray & hexEncoded)函数可以实现这个功能。
QByteArray QByteArray::fromHex(const QByteArray & hexEncoded)
Returns a decoded copy of the hex encoded array hexEncoded. Input is not checked for validity;
invalid characters in the input are skipped, enabling the decoding process to continue with subsequent characters.
For example:
QByteArray text = QByteArray::fromHex("517420697320677265617421");
text.data();
// returns "Qt is great!"
对于字符串匹配查找方面,我用的是泛型函数库algorithm中的search函数:
具体用法请到:http://www.cplusplus.com中查询,这里只给出例子:
// search algorithm example
#include // std::cout
#include// std::search
#include // std::vectorbool mypredicate (int i, int j) {
return (i==j);
}int main () {
std::vector haystack;
// set some values:haystack: 10 20 30 40 50 60 70 80 90
for (int i=1;
i<10;
i++) haystack.push_back(i*10);
// using default comparison:
int needle1[] = {40,50,60,70};
std::vector::iterator it;
it = std::search (haystack.begin(), haystack.end(), needle1, needle1+4);
if (it!=haystack.end())
std::cout << "needle1 found at position " << (it-haystack.begin()) << '\n';
else
std::cout << "needle1 not found\n";
// using predicate comparison:
int needle2[] = {20,30,50};
it = std::search (haystack.begin(), haystack.end(), needle2, needle2+3, mypredicate);
if (it!=haystack.end())
std::cout << "needle2 found at position " << (it-haystack.begin()) << '\n';
else
std::cout << "needle2 not found\n";
return 0;
}
【Qt下QByteArray的使用】Output:
needle1 found at position 3
needle2 not found
推荐阅读
- Qt|Qt常用UI控件读取、写入方法
- Qt|Qt For Android 之启动页
- QT|QT面试
- QT安装
- qt|qt for android实现app内通过按键后台运行程序
- qt|qt for android程序保活 程序后台一直运行不被清理掉(未完)
- QWidget实现手机ipad屏幕滑屏效果
- Qt|Qt官方示例-QML Axes
- 在QT/QML中使用FontAwesome做图标显示
- QT|QtCreator2.7.0桌面快捷方式创建过程