c语言 int与byte[]互相转换

本文介绍了一个C语言程序,该程序演示了如何将int类型的数据转换为byte数组以及如何从byte数组还原回int类型。通过使用位操作和内存分配函数,文章详细展示了整个转换过程,并通过gdb调试工具验证了转换的正确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

gdb调试

root@ubuntu:/media/mtk6795/alps/sunwave_pub# gcc -g test.c 
root@ubuntu:/media/mtk6795/alps/sunwave_pub# gdb ./a.out 
GNU gdb (Ubuntu/Linaro 7.4-2012.04-0ubuntu2.1) 7.4-2012.04
Copyright (C) 2012 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
For bug reporting instructions, please see:
<http://bugs.launchpad.net/gdb-linaro/>...
Reading symbols from /media/mtk6795/alps/sunwave_pub/a.out...done.
(gdb) start
Temporary breakpoint 1 at 0x40054c: file test.c, line 6.
Starting program: /media/mtk6795/alps/sunwave_pub/a.out 

Temporary breakpoint 1, main () at test.c:6
6		int a =257; 
(gdb) n
7		int a0=0,a1=0;
(gdb) 
8		unsigned char * pBuf = NULL ;
(gdb) 
9		int b=0;
(gdb) 
10		pBuf = (unsigned char*) malloc(72*128*sizeof(unsigned char));
(gdb) 
13	    pBuf[0] =(unsigned char)(a & 0xff);
(gdb) 
14		pBuf[1] = (unsigned char)((a & 0xff00) >> 8);
(gdb) 
16	    a0 = a%256;
(gdb) 
17	    a1 = a/256;
(gdb) 
19		printf("bruce int2byte  ==>> pBuf[0]=%d,pBuf[1]=%d\n",pBuf[0],pBuf[1]);
(gdb) 
bruce int2byte  ==>> pBuf[0]=1,pBuf[1]=1
20		printf("bruce int2byte  ==>> a0=%d,a1=%d\n",a0,a1);
(gdb) 
bruce int2byte  ==>> a0=1,a1=1
23		b =(int)(( pBuf[0] & 0xff )|((pBuf[1] & 0xff)<<8));
(gdb) 
24		printf("bruce byte2int  ==>> b=%d\n",b);
(gdb) 
bruce byte2int  ==>> b=257
27		return 0;
(gdb) 
28	}
(gdb) 

c语言 int与byte[]互相转换

#include<stdio.h>
#include<string.h>
#include<math.h> 
#include<stdlib.h>
int main(){
	int a =257; 
	int a0=0,a1=0;
	unsigned char * pBuf = NULL ;
	int b=0;
	pBuf = (unsigned char*) malloc(72*128*sizeof(unsigned char));

	//int2byte
    pBuf[0] =(unsigned char)(a & 0xff);
	pBuf[1] = (unsigned char)((a & 0xff00) >> 8);

    a0 = a%256;
    a1 = a/256;

	printf("bruce int2byte  ==>> pBuf[0]=%d,pBuf[1]=%d\n",pBuf[0],pBuf[1]);
	printf("bruce int2byte  ==>> a0=%d,a1=%d\n",a0,a1);

    //byte2int
	b =(int)(( pBuf[0] & 0xff )|((pBuf[1] & 0xff)<<8));
	printf("bruce byte2int  ==>> b=%d\n",b);


	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值