将NSInteger和NSString转换为字节数组

时间:2013-12-20 18:21:45

标签: ios objective-c cocoa-touch nsstring nsinteger

我需要将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 个答案:

答案 0 :(得分:5)

由于您的字符串是UUID字符串,您可以执行以下操作:

NSString *test = @"";
uuid_t uuid;
uuid_parse([test UTF8String], uuid)
NSData *data = [NSData dataWithBytes:uuid length:16];

您可以这样做的数字:

NSInteger test = 1;
NSData *data = [NSData dataWithBytes:&test length:sizeof(test)];

请记住,NSInteger可能超过两个字节,您可能还需要担心字节顺序。

更新:由于您似乎需要将整数值设置为两个字节,因此您应该执行以下操作:

uint16_t test = 1;
NSData *data = [NSData dataWithBytes:&test length:sizeof(test)];

这将确保2个字节。您还需要担心字节排序,因此您确实需要:

uint16_t test = 1;
uint16_t bytes = CFSwapInt16HostToBig(test);
NSData *data = [NSData dataWithBytes:&bytes length:sizeof(bytes)];

如果合适,请将CFSwapInt16HostToBig更改为CFSwapInt16HostToLitte