1.高低字节互换:

#define BigtoLittle16(A)   (( ((unsigned short)(A) & 0xff00) >> 8)  | (((unsigned short)(A)& 0x00ff) << 8))

假如有一个32位的数据 0x11223344,则在小端模式上的机器上存储为如下的形式:

 

C++实现上位机1:解析modbus报头

【1】0x11223344这个数中 0x11 是高字节(MSB),0x44是地字节(LSB)

【2】讨论大小端的时候最小单位是字节

【3】内存的画法中采用的是向上增长的

【3】可以将数据比作方向盘,顺时钟旋转得到的在内存中的布局是小端存储

 

至于大端模式用文字描述是,低地址上存放高字节,高地址上存放低字节。

参考文献:https://blog.csdn.net/qqliyunpeng/article/details/68484497?utm_source=copy

测试代码:

unsigned short a=sizeof(moreR_protocol_head);
	printf("a:%d\n",a);
	unsigned short b=a&0xff00;
	unsigned short e=b>>8;
	unsigned short c=a&0x00ff;
	unsigned short d=c<<8;
	printf("b:%d,e:%d,c:%d,d:%d\n",b,e,c,d);

运行结果:

C++实现上位机1:解析modbus报头

2.memcpy函数,

void *memcpy(void *dest, const void *src, size_t n);

从源src所指的内存地址的起始位置开始拷贝n个字节到目标dest所指的内存地址的起始位置中

定义结构体:

struct MBAP_head{
	short int  s_transactionIdentifier;//事务处理标识符
	short int  s_protocolIdentifier;//协议标识符
	short int s_length;//长度
	//unsigned char s_unitIdentifier;//单元标识符

	MBAP_head(){
		s_transactionIdentifier = 0;
		s_protocolIdentifier = 0;
		//s_unitIdentifier = 0x01;
	}
};

将一个结构体拷贝到一个字符数组时,依次将结构体的成员变量拷贝到字符数组中,拷贝结果如下图:

C++实现上位机1:解析modbus报头

源代码:

// C_Upper.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

struct moreR_protocol_head{
	unsigned char s_stack_address;//栈地址
	unsigned char s_function_code;//功能码
	short int s_Register_Address;//起始地址
	short int s_Register_Number;//寄存器数量
	moreR_protocol_head(){
		s_stack_address = 0x01;
		s_function_code = 0x03;
	}
};
struct MBAP_head{
	short int  s_transactionIdentifier;//事务处理标识符
	short int  s_protocolIdentifier;//协议标识符
	short int s_length;//长度
	//unsigned char s_unitIdentifier;//单元标识符

	MBAP_head(){
		s_transactionIdentifier = 0;
		s_protocolIdentifier = 0;
		//s_unitIdentifier = 0x01;
	}
};
#define BigtoLittle16(A)   (( ((unsigned short)(A) & 0xff00) >> 8)  | (((unsigned short)(A)& 0x00ff) << 8))
#define PACK_MAX_SIZE 512
int _tmain(int argc, _TCHAR* argv[])
{
	unsigned short a=sizeof(moreR_protocol_head);
	printf("a:%d\n",a);
	unsigned short b=a&0xff00;
	unsigned short e=b>>8;
	unsigned short c=a&0x00ff;
	unsigned short d=c<<8;
	printf("b:%d,e:%d,c:%d,d:%d\n",b,e,c,d);
	MBAP_head l_MBAP;
	l_MBAP.s_length = BigtoLittle16(sizeof(moreR_protocol_head));//
	printf("l_MBAP.s_length:%d\n",l_MBAP.s_length);
	unsigned char m_result[PACK_MAX_SIZE];
	memcpy(m_result, &l_MBAP, sizeof(l_MBAP));
	
	return 0;
}

 

 

 

相关文章:

  • 2021-12-10
  • 2022-12-23
  • 2022-12-23
  • 2021-04-05
  • 2021-10-29
  • 2022-12-23
  • 2021-09-25
  • 2021-08-24
猜你喜欢
  • 2022-12-23
  • 2021-07-01
  • 2022-12-23
  • 2021-12-09
相关资源
相似解决方案