1 截取byte[]中一部分数据,从begin 开始,长度是 count
- (void)bytesplit2byte:(Byte[])src orc:(Byte[])orc begin:(NSInteger)begin count:(NSInteger)count{
memset(orc, 0, sizeof(char)*count);
for (NSInteger i = begin; i < begin+count; i++){
orc[i-begin] = src[i];
}
}
2 把 byte数组转成 Int类型的数据,这 提供了一种 存储思想
-(int) lBytesToInt:(Byte[]) byte
{
int height = 0;
NSData * testData =[NSData dataWithBytes:byte length:4];
for (int i = 0; i < [testData length]; i++)
{
if (byte[[testData length]-i] >= 0)
{
height = height + byte[[testData length]-i];
} else
{
height = height + 256 + byte[[testData length]-i];
}
height = height * 256;
}
if (byte[0] >= 0)
{
height = height + byte[0];
} else {
height = height + 256 + byte[0];
}
return height;
}
3 把 int 转成 byte[]
int jsonlen = JsonData.length;
char *p_json = (char *)&jsonlen;
char str_json[4] = {0};
for(int i= 0 ;i < 4 ;i++)
{
str_json[i] = *p_json;
p_json ++;
}
具体使用地方,例如,自定义socket协议。需要传入 数据大小,需要将 int的长度,转成byte[] 这样放入对应协议的字节中才可以

本文介绍如何在编程中实现byte数组与整型数据之间的转换:一是如何从byte[]中截取特定部分;二是如何将byte数组转换为int类型,并提出一种存储思路;三是介绍如何将int类型数据转换为byte[],适用于自定义socket协议等场景。

3560

被折叠的 条评论
为什么被折叠?



