Question

I need to represent a NSInteger and NSString into array of bytes. below are the sample of what I am looking for.

For how, this harcodings are working fine. I want to do this through code. Any clue.

First, NSInteger into bytes of 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)];

Second, NSString into bytes of Hex:

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)];

I tried with below code and it works well for my UUID but for NSInteger to to be working I need to send "0010" instead of 16 and "0001" instead of 1. So any clue on how to do this conversion.

- (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;
}

EDIT:

int8_t test = -59;
int8_t bytes = CFSwapInt16HostToBig(test);
NSData *data1 = [NSData dataWithBytes:&bytes length:sizeof(bytes)];

Reaching as 0xFF instead of 0xC4

Was it helpful?

Solution

Since your string is a UUID string you can do something like this:

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

For the number you can do:

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

Keep in mind that NSInteger is probably more than two bytes and you may also need to worry about byte order.

Update: Since it seems you need the integer value to be two bytes, you should do:

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

This will ensure 2 bytes. You also need to worry about byte ordering so you really need:

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

Change CFSwapInt16HostToBig to CFSwapInt16HostToLitte if appropriate.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top