天天看點

C++實作上位機1:解析modbus報頭

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;
}