直接上代码,需要的拿走不谢。
+ (Byte *)shortToByte:(short)a {
Byte *buf = (Byte *)malloc(2);
for (int i = 1; i >= 0; i--) {
buf[i] = a & 0x00ff;
a = a >> 8;
}
return buf;
}
+(NSData*) longToByetes:(int)data {
NSMutableData * result = [[NSMutableData alloc]init];
int tmp = HTONL(data);
[result appendBytes:&tmp length:sizeof(long long)];
return result;
}
+ (Byte *)intToByte:(int)a {
Byte *buf = (Byte *)malloc(4);
for (int i = 3; i >= 0; i--) {
buf[i] = a & 0x000000ff;
a = a >> 8;
}
return buf;
}
+ (Byte *)longToByte:(long long)a {
Byte *buf = (Byte *)malloc(8);
for (int i = 7; i >= 0; i--) {
buf[i] = a & 0x00000000000000ff;
a = a >> 8;
}
return buf;
}
+ (Byte *)appIdToByte:(NSString *)appid {
NSData *appID = [appid dataUsingEncoding:NSUTF8StringEncoding];
Byte *buf = (Byte *)malloc(32);
Byte *sbuf = (Byte *)[appID bytes];
for (int i = 0; i <= 31; i++) {
buf[i] = sbuf[i];
if (i > [appID length] - 1) {
buf[i] = 0;
}
}
return buf;
}
+ (int)byteToInt:(Byte *)buf {
int value = 0;
int len = 4;
for (int i = 0; i < len; i ++) {
value = (value << 8) | buf[i];
}
return value;
}
+ (short)byteToShort:(Byte *)buf {
short value = 0;
int len = 2;
for (int i = 0; i < len; i ++) {
value = (value << 8) | buf[i];
}
return value;
}
+ (long long)byteToLongLong:(Byte *)buf {
long long value = 0;
int len = 8;
for(int i = 0; i < len; i++) {
value = (value << 8) | buf[i];
}
return value;
}