我需要将NSInteger和NSString表示为字节数组 . 以下是我要找的样本 .
对于如何,这种编码工作得很好 . 我想通过代码来做到这一点 . 任何线索 .
首先,NSInteger为Hex的字节:
NSInteger test = 1;
unsigned char byte[] = { 0x00, 0x01 };
NSInteger test = 16;
unsigned char byte[] = { 0x00, 0x10 };
NSData *data = [NSData dataWithBytes:byte length:sizeof(byte)];
二,NSString为十六进制字节:
NSString *test = @"31C5B562-BD07-4616-BCBD-130BA6822790";
unsigned char byte[] = {0x31, 0xC5, 0xB5, 0x62, 0xBD, 0x07, 0x46, 0x16, 0xBC, 0xBD, 0x13, 0x0B, 0xA6, 0x82, 0x27, 0x90};
NSData *data = [NSData dataWithBytes:byte length:sizeof(byte)];
我尝试使用下面的代码,它适用于我的UUID但是为了使NSInteger工作,我需要发送“0010”而不是16和“0001”而不是1.所以任何关于如何进行此转换的线索 .
- (NSData *)hexData {
NSMutableData *hexData = [NSMutableData data];
int idx = 0;
for (idx = 0; idx+2 <= self.length; idx+=2) {
NSRange range = NSMakeRange(idx, 2);
NSString* hexStr = [self substringWithRange:range];
NSScanner* scanner = [NSScanner scannerWithString:hexStr];
unsigned int intValue;
[scanner scanHexInt:&intValue];
[hexData appendBytes:&intValue length:1];
}
return hexData;
}
编辑:
int8_t test = -59;
int8_t bytes = CFSwapInt16HostToBig(test);
NSData *data1 = [NSData dataWithBytes:&bytes length:sizeof(bytes)];
达到0xFF而不是0xC4
1 回答
由于您的字符串是UUID字符串,您可以执行以下操作:
您可以这样做的号码:
请记住
NSInteger
可能超过两个字节,您可能还需要担心字节顺序 .更新:由于您似乎需要将整数值设置为两个字节,因此您应该:
这将确保2个字节 . 您还需要担心字节排序,因此您确实需要:
如果合适,将
CFSwapInt16HostToBig
更改为CFSwapInt16HostToLitte
.