Qt 从QByteArray类型数据恢复long in型数据

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Qt 从QByteArray类型数据恢复long in型数据相关的知识,希望对你有一定的参考价值。

发送端
long size=88888;write(tcpsocket,&size,sizeof(long));
接收端
QByteArray secdata=socket->readAll();
我该怎样从QByteArray类型的数据中恢复long型数据?????
我自己解决了,上代码
long framesize;
memcpy(&framesize,secdata.data(),sizeof(long));
得到的framesize就是88888啦!!!!

参考技术A Qt 从QByteArray类型数据恢复long in型数据
就一个数字的话,直接调用QByteArray::toInt()一类的就可以了: double toDouble ( bool * ok = 0 ) const float toFloat ( bool * ok = 0 ) const QByteArray toHex () const int toInt ( bool * ok = 0, int base = 10 ) const long toLong
参考技术B 直接用tolong这这个方法就可以,但注意不能超过7fffffff

QByteArray 在 Qt C++ 5.8.0 中翻倍

【中文标题】QByteArray 在 Qt C++ 5.8.0 中翻倍【英文标题】:QByteArray to Double in Qt C++ 5.8.0 【发布时间】:2017-06-26 05:18:34 【问题描述】:

我有一个串口数据读写程序。正在从 comport 4 读取数据(例如:1022),但是当我尝试对数据 1022/2 进行数学计算时,它给我的输出为0.5 5.0 51.00 511.0 意味着它不会将整个 1022 作为一个单一的数学计算的数字。它先取 1,然后除以 1/2=0.5,然后一旦收到 0 位,就取 10/2=5,依此类推。但我希望 1022 作为一个数字(例如:1022/2=511)

我已尝试将 QByteArray 转换为 Double 进行计算。

     void MainWindow::readData()
 
     QByteArray data = serial->readAll();
     bool ok;
     QByteArray cata= QByteArray::number(data.toDouble(&ok)/2);

    console->putData(cata);
 

【问题讨论】:

Qt 中典型的调试技术是使用qdebug();使用它来查看您是否已正确读取数据。如果您可以使用bytesAvailable() 在处理之前查看是否有任何可用数据,那就太好了。 @rakib_ 感谢您的回复,我已经用 qdebug() 检查了它是否垂直接收相同的数据。我希望将数据转换为双精度数据,并对收到的数据进行一些数学计算。谢谢你.. 在串行通信中,数字是一串序列化的数据。不可能按原样发送 1022 号码。它将在代码中吐出“0”的“1”代码,依此类推。您必须做的是知道字节如何组成您的号码,将其分组,然后将原始数据转换为您的有效号码。 你也可以将你的双精度作为一个字符串发送,发送它,接收字符串(你可以找到很多关于它的例子),然后使用 QVariant 将它作为双精度返回。 【参考方案1】:

这里是 Qt 中 TCP 客户端/服务器 的示例。服务器发送 1022.72,客户端接收并显示除以 2 的结果值。(运行服务器然后客户端:

服务器代码:

test.pro:

#-------------------------------------------------
#
# Project created by QtCreator 2017-06-26T12:49:54
#
#-------------------------------------------------

QT       += core gui network

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = test
TEMPLATE = app

# The following define makes your compiler emit warnings if you use
# any feature of Qt which as been marked as deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS

# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0


SOURCES += main.cpp\
        mainwindow.cpp

HEADERS  += mainwindow.h

FORMS    += mainwindow.ui

main.cpp:

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])

    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();

主窗口.cpp:

#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QDebug>
#include <QHostAddress>
#include <QAbstractSocket>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    _server(this)

    ui->setupUi(this);
    _server.listen(QHostAddress::Any, 4242);
    connect(&_server, SIGNAL(newConnection()), this, SLOT(onNewConnection()));


MainWindow::~MainWindow()

    delete ui;



void MainWindow::onNewConnection()

   QTcpSocket *clientSocket = _server.nextPendingConnection();
   connect(clientSocket, SIGNAL(readyRead()), this, SLOT(onReadyRead()));
   connect(clientSocket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(onSocketStateChanged(QAbstractSocket::SocketState)));

    _sockets.push_back(clientSocket);
    for (QTcpSocket* socket : _sockets) 
        double data = 1022.72;
//        socket->write(QByteArray::fromStdString(clientSocket->peerAddress().toString().toStdString() + " connected to server !\n"));
        socket->write(QByteArray::fromStdString(QVariant(data).toString().toStdString()));
    


void MainWindow::onSocketStateChanged(QAbstractSocket::SocketState socketState)

    if (socketState == QAbstractSocket::UnconnectedState)
    
        QTcpSocket* sender = static_cast<QTcpSocket*>(QObject::sender());
        _sockets.removeOne(sender);
    


void MainWindow::onReadyRead()

    QTcpSocket* sender = static_cast<QTcpSocket*>(QObject::sender());
    QByteArray datas = sender->readAll();
    for (QTcpSocket* socket : _sockets) 
        if (socket != sender)
            socket->write(QByteArray::fromStdString(sender->peerAddress().toString().toStdString() + ": " + datas.toStdString()));
    

主窗口.h:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QTcpServer>
#include <QTcpSocket>

namespace Ui 
class MainWindow;


class MainWindow : public QMainWindow

    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

public slots:
    void onNewConnection();
    void onSocketStateChanged(QAbstractSocket::SocketState socketState);
    void onReadyRead();
private:
    Ui::MainWindow *ui;
    QTcpServer  _server;
    QList<QTcpSocket*>  _sockets;
;

#endif // MAINWINDOW_H

mainwindow.ui:(空)

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>400</width>
    <height>300</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>MainWindow</string>
  </property>
  <widget class="QWidget" name="centralWidget">
   <layout class="QVBoxLayout" name="verticalLayout_2">
    <item>
     <layout class="QVBoxLayout" name="verticalLayout"/>
    </item>
   </layout>
  </widget>
  <widget class="QMenuBar" name="menuBar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>400</width>
     <height>25</height>
    </rect>
   </property>
  </widget>
  <widget class="QToolBar" name="mainToolBar">
   <attribute name="toolBarArea">
    <enum>TopToolBarArea</enum>
   </attribute>
   <attribute name="toolBarBreak">
    <bool>false</bool>
   </attribute>
  </widget>
  <widget class="QStatusBar" name="statusBar"/>
 </widget>
 <layoutdefault spacing="6" margin="11"/>
 <resources/>
 <connections/>
</ui>

客户端代码:

test2.pro:

#-------------------------------------------------
#
# Project created by QtCreator 2017-06-26T14:34:11
#
#-------------------------------------------------

QT       += core gui network

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = test2
TEMPLATE = app

# The following define makes your compiler emit warnings if you use
# any feature of Qt which as been marked as deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS

# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0


SOURCES += main.cpp\
        mainwindow.cpp

HEADERS  += mainwindow.h

FORMS    += mainwindow.ui

main.cpp:

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])

    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();

主窗口.cpp:

#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QDebug>
#include <QHostAddress>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    _socket(this)

    ui->setupUi(this);
    _socket.connectToHost(QHostAddress("127.0.0.1"), 4242);
    connect(&_socket, SIGNAL(readyRead()), this, SLOT(onReadyRead()));


MainWindow::~MainWindow()

    delete ui;


void MainWindow::onReadyRead()

    QByteArray datas = _socket.readAll();

    qDebug() << QVariant(datas).toDouble() / 2;

    ui->label->setText(QVariant(QVariant(datas).toDouble() / 2).toString());

    _socket.write(QByteArray("ok !\n"));

主窗口.h:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QTcpSocket>

namespace Ui 
class MainWindow;


class MainWindow : public QMainWindow

    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

public slots:
    void onReadyRead();

private:
    Ui::MainWindow *ui;
    QTcpSocket  _socket;
;

#endif // MAINWINDOW_H

mainwindow.ui: (结果写在这里,也用 qDebug)

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>400</width>
    <height>300</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>MainWindow</string>
  </property>
  <widget class="QWidget" name="centralWidget">
   <layout class="QVBoxLayout" name="verticalLayout_2">
    <item>
     <layout class="QVBoxLayout" name="verticalLayout">
      <item>
       <widget class="QLabel" name="label">
        <property name="text">
         <string/>
        </property>
       </widget>
      </item>
     </layout>
    </item>
   </layout>
  </widget>
  <widget class="QMenuBar" name="menuBar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>400</width>
     <height>25</height>
    </rect>
   </property>
  </widget>
  <widget class="QToolBar" name="mainToolBar">
   <attribute name="toolBarArea">
    <enum>TopToolBarArea</enum>
   </attribute>
   <attribute name="toolBarBreak">
    <bool>false</bool>
   </attribute>
  </widget>
  <widget class="QStatusBar" name="statusBar"/>
 </widget>
 <layoutdefault spacing="6" margin="11"/>
 <resources/>
 <connections/>
</ui>

【讨论】:

@Elia 我该怎么做我不知道该怎么做。你能告诉我吗?

以上是关于Qt 从QByteArray类型数据恢复long in型数据的主要内容,如果未能解决你的问题,请参考以下文章

如何将qt中的qbytearray类型数据转换成去qstring类型

写了一个QT程序和一个C程序,如何把QT程序里发出的QByteArray类型数据,让C程序接收到或者是处理识别?

从QDataStream向QByteArray中写入数据时的注意点(QT)

从 QByteArray 解析 QT5 JSON

Qt 学习笔记 4. QByteArray

如何从 QByteArray 获取结构