比如用Long Long存3个数据的内容。
这里要知道大小端的知识点。
方法一是用位运算;
方法二是用指针;
方法三是结构体(本质上也是指针);
运行截图如下:
源码如下:
main.cpp
1 #include <iostream>
2 using namespace std;
3
4 struct SplitLongLong{
5 short shortValue2;
6 short shortValue1;
7 int intValue;
8 };
9
10 void main(){
11
12 long long myTestLongLong=1234605616436508552;
13 cout<<"hexadecimal original data: "<<hex<<"0x:"<<myTestLongLong<<endl;
14 cout<<"decimalism original data:"<<dec<<myTestLongLong<<endl<<endl;
15
16 //The first method!
17 cout<<"The first method!"<<endl;
18 int method1_int=(int)(myTestLongLong>>4*8); //Little-endian
19 short method1_short1=(short)(myTestLongLong>>2*8);
20 short method1_short2=(short)(myTestLongLong);
21
22 cout<<"hexadecimal 0x"<<hex<<method1_int<<" 0x"<<method1_short1<<" 0x"<<method1_short2<<endl;
23 cout<<"decimalism "<<dec<<method1_int<<" "<<method1_short1<<" "<<method1_short2<<endl<<endl;
24
25 long long method1_long=((long long)method1_int<<4*8)+((long long)method1_short1<<2*8)+((long long)method1_short2);
26 cout<<"hexadecimal combined data :0x"<<hex<<method1_long<<endl;
27 cout<<"decimalism combined data :"<<dec<<method1_long<<endl<<endl;
28
29 //The second method!
30 cout<<"The second method!"<<endl;
31 char *ptr=(char *)(&myTestLongLong);
32 int method2_int = *(int *)(ptr+4); //Little-endian
33 short method2_short1 = *(short*)(ptr+2);
34 short method2_short2 = *(short*)ptr;
35 cout<<"hexadecimal 0x"<<hex<<method2_int<<" 0x"<<method2_short1<<" 0x"<<method2_short2<<endl;
36 cout<<"decimalism "<<dec<<method2_int<<" "<<method2_short1<<" "<<method2_short2<<endl<<endl;
37
38 long long method2_long;
39 ptr=(char*)(&method2_long);
40 *(short*)ptr=method2_short2;
41 *(short*)(ptr+2)=method2_short1;
42 *(int*)(ptr+4)=method2_int;
43 cout<<"hexadecimal combined data :0x"<<hex<<method2_long<<endl;
44 cout<<"decimalism combined data :"<<dec<<method2_long<<endl<<endl;
45
46
47
48 //The third method!
49 cout<<"The third method!"<<endl;
50 SplitLongLong split;
51 split=*(SplitLongLong*)&myTestLongLong;
52 cout<<"hexadecimal 0x"<<hex<<split.intValue<<" 0x"<<split.shortValue1<<" 0x"<<split.shortValue2<<endl;
53 cout<<"decimalism "<<dec<<split.intValue<<" "<<split.shortValue1<<" "<<split.shortValue2<<endl<<endl;
54
55 long long method3_long;
56 ptr=(char*)(&method3_long);
57 *(short*)ptr=split.shortValue2;
58 *(short*)(ptr+2)=split.shortValue1;
59 *(int*)(ptr+4)=split.intValue;
60 cout<<"hexadecimal combined data :0x"<<hex<<method3_long<<endl;
61 cout<<"decimalism combined data :"<<dec<<method3_long<<endl<<endl;
62
63 getchar();
64 }