C++工作笔记-3种方法对数据类型进行拆分(可用于各种协议)
生活随笔
收集整理的這篇文章主要介紹了
C++工作笔记-3种方法对数据类型进行拆分(可用于各种协议)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
比如用Long Long存3個(gè)數(shù)據(jù)的內(nèi)容。
這里要知道大小端的知識點(diǎn)。
方法一是用位運(yùn)算;
方法二是用指針;
方法三是結(jié)構(gòu)體(本質(zhì)上也是指針);
運(yùn)行截圖如下:
源碼如下:
main.cpp
#include <iostream> using namespace std;struct SplitLongLong{short shortValue2;short shortValue1;int intValue; };void main(){long long myTestLongLong=1234605616436508552;cout<<"hexadecimal original data: "<<hex<<"0x:"<<myTestLongLong<<endl;cout<<"decimalism original data:"<<dec<<myTestLongLong<<endl<<endl;//The first method! cout<<"The first method!"<<endl;int method1_int=(int)(myTestLongLong>>4*8); //Little-endianshort method1_short1=(short)(myTestLongLong>>2*8);short method1_short2=(short)(myTestLongLong);cout<<"hexadecimal 0x"<<hex<<method1_int<<" 0x"<<method1_short1<<" 0x"<<method1_short2<<endl;cout<<"decimalism "<<dec<<method1_int<<" "<<method1_short1<<" "<<method1_short2<<endl<<endl;long long method1_long=((long long)method1_int<<4*8)+((long long)method1_short1<<2*8)+((long long)method1_short2);cout<<"hexadecimal combined data :0x"<<hex<<method1_long<<endl;cout<<"decimalism combined data :"<<dec<<method1_long<<endl<<endl;//The second method!cout<<"The second method!"<<endl;char *ptr=(char *)(&myTestLongLong);int method2_int = *(int *)(ptr+4); //Little-endianshort method2_short1 = *(short*)(ptr+2);short method2_short2 = *(short*)ptr;cout<<"hexadecimal 0x"<<hex<<method2_int<<" 0x"<<method2_short1<<" 0x"<<method2_short2<<endl;cout<<"decimalism "<<dec<<method2_int<<" "<<method2_short1<<" "<<method2_short2<<endl<<endl;long long method2_long;ptr=(char*)(&method2_long);*(short*)ptr=method2_short2;*(short*)(ptr+2)=method2_short1;*(int*)(ptr+4)=method2_int;cout<<"hexadecimal combined data :0x"<<hex<<method2_long<<endl;cout<<"decimalism combined data :"<<dec<<method2_long<<endl<<endl;//The third method!cout<<"The third method!"<<endl;SplitLongLong split;split=*(SplitLongLong*)&myTestLongLong;cout<<"hexadecimal 0x"<<hex<<split.intValue<<" 0x"<<split.shortValue1<<" 0x"<<split.shortValue2<<endl;cout<<"decimalism "<<dec<<split.intValue<<" "<<split.shortValue1<<" "<<split.shortValue2<<endl<<endl;long long method3_long;ptr=(char*)(&method3_long);*(short*)ptr=split.shortValue2;*(short*)(ptr+2)=split.shortValue1;*(int*)(ptr+4)=split.intValue;cout<<"hexadecimal combined data :0x"<<hex<<method3_long<<endl;cout<<"decimalism combined data :"<<dec<<method3_long<<endl<<endl;getchar(); }?
總結(jié)
以上是生活随笔為你收集整理的C++工作笔记-3种方法对数据类型进行拆分(可用于各种协议)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Qt工作笔记-undefined ref
- 下一篇: Qt工作笔记-QString中Split