当前位置:网站首页>主机字节序的判定
主机字节序的判定
2022-07-23 05:44:00 【lhb2998658795】
1.1字节序判定的基础知识以及判定
不同类型CPU的主机中,内存存储多字节整数序列有两种方法,称为主机字节序(HBO):
小端序(little-endian) - 的序字节存储在低地址
将低字节存储在起始地址,称为“Little-Endian”字节序,Intel、AMD等采用的是这种方式;
大端序(big-endian)- 高序字节存储在低地址
将高字节存储在起始地址,称为“Big-Endian”字节序,由ARM、Motorola等所采用
1.1.1字节序判定的原理图

1.1.2字节序判定的方法
#include <stdio.h>
int main(int argc, char const *argv[])
{
int num=0x12345678;
char *p=(char *)#//这个地方加强转防止爆警告
if(*p==0x12){
printf("这是大端字节序\n");
}else if(*p==0x78){
printf("这是小端字节序\n");
}
return 0;
}
union联合体是共用一块内存,所以可以使用这种方法测试
#include <stdio.h>
typedef union {
char a;
int b;
}msg_t;
int main(int argc, char const *argv[])
{
msg_t num;
num.b=0x12345678;
if(num.a==0x78){
printf("这是小端字节序\n");
}else if(num.a==0x12){
printf("这是大端字节序\n");
}
return 0;
}2.2什么情况下需要考虑字节序转换的问题
2.2.1判定情况
如果数据是1个字节的,无需考虑字节序的问题和如果明确知道通信的双方主机字节序一样,也可以不考虑,如果超过了1个字节的数据作为一个整体时,就需要考虑了。
2.2.2将小端序的无符号四字节整型转换成大端序,也就是转换原理
#include <stdio.h>
int main(int argc, char const *argv[])
{
unsigned int num=0x12345678;
char *p=(char *)#
char *q=p+3;
unsigned char temp;
temp=*p;
*p=*q;
*q=temp;
p++;
q--;
temp=*p;
*p=*q;
*q=temp;
printf("%#x\n",num);
return 0;
}2.3字节序转换函数
2.3.1函数
h host 主机 n network 网络 l 长 s 短
uint32_t htonl(uint32_t hostlong);//主机转网络 4字节
uint16_t htons(uint16_t hostshort);//主机转网络 2字节
uint32_t ntohl(uint32_t netlong);//网络转主机 4字节
uint16_t ntohs(uint16_t netshort);//网络转主机 2字节
2.3.2函数使用
#include <arpa/inet.h>
#include <stdio.h>
int main(int argc, char const *argv[])
{
unsigned int num=0x12345678;
unsigned int m=htonl(num);
printf("%#x\n",m);
return 0;
}
边栏推荐
猜你喜欢

博客搭建六:绑定自己域名的方法

Examen des principes fondamentaux de la structure en acier

【Autosar 存储Stack NVM】

A comprehensive and detailed summary of the basic principles of steel structure

【AUTOSAR DCM 1.模块简介(DSL,DSD,DSP)】

钢结构基本原理全面详细总结

Questions and answers of basic principles of steel structure

常见的排序—交换排序

【AUTOSAR COM 3.信号的收发流程TX/RX】

Blog building five: drawing bed selection
随机推荐
基于对象(Object Based)-两个经典类
5.4 installation and use of pyinstaller Library
[AUTOSAR DEM iv.event memory]
Interpretation of the paper: develop a prediction model based on multi-layer deep learning to identify DNA N4 methylcytosine modification
高电压技术复习资料
Baidu Shen Shuo: focus on the scene, deeply cultivate the industry, and bring practical results to enterprise Digitalization
[AUTOSAR CP general 1. how to read AUTOSAR official documents]
Related repo of synthetic Chinese recognition dataset
【存储器了解 RAM flash和eeprom存储器的区别和作用】
【AUTOSAR CanTP 1.学习UDS诊断的网络层协议】
The CUDA version of pytorch installed by anconda is inconsistent with the CUDA version of the system
K-nucleotide frequencies (KNF) or k-mer frequencies
对字符串函数的使用和理解(2)
Blog Building II: next theme related settings beta
动态规划——“换硬币问题”
鋼結構基本原理複習
Object based - two classic classes
Interpretation of the paper: the interpretability of the transformer model of functional genomics
永磁电机参数的测量获取(电感、电阻、极对数、磁链常数)
Vs attribute configuration related knowledge