最近做一个项目 要传udp包 包里包含很多信息 就是把一些信息用byte表示
所以包含很多byte的转换 这里记录一下 在网上没查到 只有int的转换
这里的例子是8个字节代表一个long long数据。
long long转为byte数组
+ (Byte*)longlongToByte:(long long)value
{
Byte * byte = malloc(8);
byte[0] = ((value>>56) & 0xFF);
byte[1] = ((value>>48) & 0xFF);
byte[2] = ((value>>40) & 0xFF);
byte[3] = ((value>>32) & 0xFF);
byte[4] = ((value>>24) & 0xFF);
byte[5] = ((value>>16) & 0xFF);
byte[6] = ((value>>8) & 0xFF);
byte[7] = (value & 0xFF);
return byte;
}
byte数组转为long long
+ (longlong)byteToLongLong:(Byte*)byte
{
longlongvalue =0;
value = (((longlong)byte[0] <<56&0xFF00000000000000L)|
((longlong)byte[1] <<48&0xFF000000000000L)|
((longlong)byte[2] <<40&0xFF0000000000L)|
((longlong)byte[3] <<32&0xFF00000000L)|
((longlong)byte[4] <<24&0xFF000000L)|
((longlong)byte[5] <<16&0xFF0000L)|
((longlong)byte[6] <<8&0xFF00L)|
((longlong)byte[7] &0xFFL));
returnvalue;
}