高低字节转换例子

来源:互联网 发布:淘宝直通车最低充值 编辑:程序博客网 时间:2024/05/01 17:14
// ConvertData.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"//#define cdr_int32_to(from) \//    ( (((from) & (0xfful << 24)) >> 24) \//    | (((from) & (0xfful << 16)) >> 8) \//    | (((from) & (0xfful << 8)) << 8) \//    | (((from) & 0xfful) << 24) )#define cdr_int32_to(from) \    ( (((from) & (0xff << 24)) >> 24) \    | (((from) & (0xff << 16)) >> 8) \    | (((from) & (0xff << 8)) << 8) \    | (((from) & 0xff) << 24) )struct MysDI{    unsigned int mydi1 :1;    unsigned int mydi2 :1;};struct struct_data{    int a;    int b;    MysDI myDI;};int _tmain(int argc, _TCHAR* argv[]){        //system("color 2");    int data = 0x12345678;    //dataConvert(data);    //data = ( (((data) & (0xfful << 24)) >> 24) | (((data) & (0xfful << 16)) >> 8)     | (((data) & (0xfful << 8)) << 8)     | (((data) & 0xfful) << 24) );    data = ( (((data) & (0xff << 24)) >> 24) | (((data) & (0xff << 16)) >> 8)     | (((data) & (0xff << 8)) << 8) | (((data) & 0xff) << 24) );    cdr_int32_to(data);    char buffer[20];    char buffer1[20];    //char *pBuff = (char*)&data;    memset(buffer,0,sizeof(buffer));    memset(buffer1,0,sizeof(buffer1));    buffer[3] =  *(char*)&data;    buffer[2] =  *((char*)&data+1);    buffer[1] =  *((char*)&data+2);    buffer[0] =  *((char*)&data+3);    buffer1[0] =  *(char*)&data;    buffer1[1] =  *((char*)&data+1);    buffer1[2] =  *((char*)&data+2);    buffer1[3] =  *((char*)&data+3);    //printf("data source ----> %f \n", data);    //printf("dataConvert ----> %f \n", /*data*/*(float*)buffer);    //printf("dataConvert1 ----> %f \n", /*data*/*(float*)buffer1);    //================test struct======================    struct_data Mystruct,fromPLC;    Mystruct.a = Mystruct.b = 0x12345678;    Mystruct.myDI.mydi1 =  1;    Mystruct.myDI.mydi2 = 0;    char *p = (char*)&fromPLC;    printf("data source ----> %x, %x \n", Mystruct.a,Mystruct.b,         Mystruct.myDI.mydi1,Mystruct.myDI.mydi2);    char struct_buffer[20],convert_buff[20];    memset(struct_buffer,0,sizeof(struct_buffer));    memset(convert_buff,0,sizeof(convert_buff));    memcpy(struct_buffer,&Mystruct,sizeof(struct_data));    memcpy(convert_buff,&Mystruct,sizeof(struct_data));    //for (int i = 0; i < 2; i ++)    //{    //    convert_buff[i*4 + 0] = struct_buffer[i*4 + 3];     //    convert_buff[i*4 + 1] = struct_buffer[i*4 + 2];     //    convert_buff[i*4 + 2] = struct_buffer[i*4 + 1];     //    convert_buff[i*4 + 3] = struct_buffer[i*4 + 0];     //}    //memcpy(&fromPLC,convert_buff,sizeof(struct_data));    for (int i = 0; i < 2; i ++)    {        p[i*4 + 0] = struct_buffer[i*4 + 3];         p[i*4 + 1] = struct_buffer[i*4 + 2];         p[i*4 + 2] = struct_buffer[i*4 + 1];         p[i*4 + 3] = struct_buffer[i*4 + 0];     }        printf("data convert ----> %x, %x \n", fromPLC.a,fromPLC.b);    printf("data convert ----> %d, %d \n", fromPLC.myDI.mydi1,fromPLC.myDI.mydi2);    return 0;}
原创粉丝点击