DJean
DJean

Reputation: 334

Convert NSInteger to bytes

I want construct a NSData object that contents 3 NSInteger type, and I do with follow codes:

- (void)test
{

    NSInteger i = 12, j = 2000, k = 2;

    NSMutableData *md = [NSMutableData dataWithCapacity:10];

    [md appendBytes:&i length:sizeof(i)];
    [md appendBytes:&j length:sizeof(j)];
    [md appendBytes:&k length:sizeof(k)];

    NSLog(@"data is %@",md);
}

But when I log it, it shows me that:

data is <0c000000 d0070000 02000000>

I translate these into decimal, these number are 201326592, 3490119680, 33554432. So I don't know why is these numbers, what should I do? Thanks.

Upvotes: 2

Views: 2587

Answers (2)

DJean
DJean

Reputation: 334

At last I folowed Marcelo's answer,and find this API can work well for me:

- (void)test
{

    NSInteger i = 12, j = 2000, k = 2;

    NSInteger i2 =  CFSwapInt32HostToBig(i);
    NSInteger j2 = CFSwapInt32HostToBig(j);
    NSInteger k2 = CFSwapInt32HostToBig(k);


    NSMutableData *md = [NSMutableData dataWithCapacity:10];

    [md appendBytes:&i2 length:sizeof(i2)];
    [md appendBytes:&j2 length:sizeof(j2)];
    [md appendBytes:&k2 length:sizeof(k2)];


    NSLog(@"data is %@",md);

}

Log:

data is <0000000c 000007d0 00000002>

Upvotes: 3

Marcelo Cantos
Marcelo Cantos

Reputation: 185852

You are on a little-endian architecture, which means that the LSB (least-significant byte) comes first. The sequence 0c 00 00 00 represents the number 00 00 00 0c, which is 12.

Upvotes: 7

Related Questions