Objective-C 中Socket常用转换机制(NSData,NSString,int,Uint8,Uint16,Uint32,byte[])
时间: 2024-02-23 17:03:35 浏览: 114
go语言中int和byte转换方式
在 Objective-C 中,常用的 Socket 转换机制如下:
1. NSData 和 NSString 之间的转换:
NSData 转 NSString:
```objective-c
NSData *data = ...;
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
```
NSString 转 NSData:
```objective-c
NSString *string = ...;
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
```
2. int 和 NSData 之间的转换:
int 转 NSData:
```objective-c
int num = ...;
NSData *data = [NSData dataWithBytes:&num length:sizeof(num)];
```
NSData 转 int:
```objective-c
NSData *data = ...;
int num;
[data getBytes:&num length:sizeof(num)];
```
3. Uint8、Uint16、Uint32 和 NSData 之间的转换:
Uint8、Uint16、Uint32 转 NSData:
```objective-c
uint8_t num8 = ...;
uint16_t num16 = ...;
uint32_t num32 = ...;
NSMutableData *data = [NSMutableData data];
[data appendBytes:&num8 length:sizeof(num8)];
[data appendBytes:&num16 length:sizeof(num16)];
[data appendBytes:&num32 length:sizeof(num32)];
```
NSData 转 Uint8、Uint16、Uint32:
```objective-c
NSData *data = ...;
uint8_t num8;
uint16_t num16;
uint32_t num32;
[data getBytes:&num8 range:NSMakeRange(0, sizeof(num8))];
[data getBytes:&num16 range:NSMakeRange(sizeof(num8), sizeof(num16))];
[data getBytes:&num32 range:NSMakeRange(sizeof(num8) + sizeof(num16), sizeof(num32))];
```
4. byte[] 和 NSData 之间的转换:
byte[] 转 NSData:
```objective-c
unsigned char bytes[] = {...};
NSData *data = [NSData dataWithBytes:bytes length:sizeof(bytes)];
```
NSData 转 byte[]:
```objective-c
NSData *data = ...;
unsigned char bytes[data.length];
[data getBytes:bytes length:data.length];
```
阅读全文