20-Qt中数据通信与数据保存用到的强制类型转换(C++类型强制转换)

在软件开发中经常会用到一些类型转换,本文所列出的类型转换是在做一个项目中所使用到的所有类型转换。在项目中把这几个类型转换单独封装成了通用类。以下分别介绍。

一、ByteUtil

在电脑软件和硬件设备通信的开发中,经常用到这个类。在这类软件中需要把电脑软件代码所使用的数据类型转换为与硬件通信协议所规定的格式。(通信协议里面的格式一般按照byte位类做设计)。

使用情形举例:
定义“typedef unsigned char byte;”。在代码中以byte为基本单位,生成了通信协议所规定的数据格式的数据(数组或结构体)。但是在所有开发平台上发送数据的write函数所使用的参数都是“char*”。而要发送的数据类型是“byte*”。因此这里需要类型转换。避免报错或报警告。注意:char 和 unsigned char 在c++语言中是两个不同定义的基础数据类型。因此相互之间不能直接赋值。 这里转换类型后能正确使用且完成通信,是因为char和byte 都是8bit的数据类型。

类的代码如下:
byteutil.h

#ifndef BYTEUTIL_H
#define BYTEUTIL_H

typedef unsigned char byte;

namespace MyUtil {
   

class ByteUtil
{
   
private:
	ByteUtil();

public:
	static char Byte2Char(const byte byte);
	static byte Char2Byte(const char ch);
	
	static char Int2Char(const int value);//only last 8bit of int is saved
	static int Char2Int(const char ch);
	
	static void ByteArray2CharArray(const byte * src, char *dst, int len);
	static void CharArray2ByteArray(const char * src, byte *dst, int len);
};
} //namespace MyUtil

#endif // BYTEUTIL_H

byteutil.cpp

#include "byteutil.h"

namespace MyUtil {
   

ByteUtil::ByteUtil()
{
   

}

char ByteUtil::Byte2Char(const byte byte) {
   
	char ret = 0x00;
	ret = ret | byte;
	return ret;
}

byte ByteUtil::Char2Byte(const char ch) {
   
	byte by = 0x00;
	by = static_cast<byte>(by | ch);
	return by;
}

//only last 8bit of int is saved
char ByteUtil::Int2Char(const int value) {
   
	return By
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值