(1)系统函数,便捷
#include <stdio.h>
#include <stdlib.h>
har* ddd = "0X00032816";
long i = strtol(ddd, nullptr, 16);
printf("i=%d\r\n",i);
//i=206870
(2)记录前人,方便自己查看, 运行结果:
代码段:
//功能:对各个字(2B)的两个字节,进行位置交换操作。
void swap_word(unsigned char *pArray, int nWords)
{
unsigned char *cc = pArray, c0;
int i;
for (i = 0; i < nWords; i ++)// Swap every two bytes
{
c0 = *cc;
*cc = *(cc + 1);
*(cc + 1) = c0;
cc += 2;
}
}
//功能: 对各个双字(4B)的两个字(2B),进行位置交换操作。
void swap_double_word(unsigned char *pArray, int nDWords)
{
unsigned char *cc = pArray, c0;
int i;
for (i = 0; i < nDWords; i ++) // Rotate every four bytes
{
// Swap first and last bytes
c0 = *cc;
*cc = *(cc + 3);
*(cc + 3) = c0;
// Swap middle two bytes
c0 = *(cc + 2);
*(cc + 2) = *(cc + 1);
*(cc + 1) = c0;
cc += 4;
}
}
int bytes_to_int_little_endian(unsigned char* src, int offset) {
int value;
value = (int) ((src[offset] & 0xFF)
| ((src[offset + 1] & 0xFF) << 8)
| ((src[offset + 2] & 0xFF) << 16)
| ((src[offset + 3] & 0xFF) << 24));
return value;
}
int bytes_to_int_big_endian(unsigned char* src, int offset) {
int value;
value = (int) (((src[offset] & 0xFF)<< 24)
| ((src[offset+1] & 0xFF)<< 16)
| ((src[offset+2] & 0xFF)<< 8)
| (src[offset+3] & 0xFF));
return value;
}
int main(int argc, char *argv[])
{
int value = 0;
unsigned char tmp[4]; memset(tmp,0x00,sizeof(tmp));
tmp[0]=0x16; tmp[1]=0x28; tmp[2]=0x03; tmp[3]=0x00;
swap_double_word(tmp,2);
printf("swap_double_word=[%02x],[%02x],[%02x],[%02x] ",tmp[0],tmp[1],tmp[2],tmp[3]);
value = bytes_to_int_little_endian(tmp,0);
printf("little_endian=[%02x],[%02x],[%02x],[%02x] value=%d",tmp[0],tmp[1],tmp[2],tmp[3],value);
value = bytes_to_int_big_endian(tmp,0);
printf("big_endian=[%02x],[%02x],[%02x],[%02x] value=%d",tmp[0],tmp[1],tmp[2],tmp[3],value);
}