比如用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 }
分类:
C/C++
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期
· 全程使用 AI 从 0 到 1 写了个小工具
· 从文本到图像:SSE 如何助力 AI 内容实时呈现?(Typescript篇)