質問

I have an NSMutableData holding random ASCII bytes. I would like to shift the values of those bytes by a value (X).

So let us say I have something like this:

02 00 02 4e 00

I now want to increase every single byte by 0x01 to get:

03 01 03 4f 01

What is the best approach for this?

役に立ちましたか?

解決

Use mutableBytes to get a pointer to your bytes, and treat them like a normal C array.

uint8_t originalBytes[] = {0x02, 0x00, 0x02, 0x4e, 0x00};
NSMutableData * myData = [NSMutableData dataWithBytes:originalBytes length:5];

uint8_t * bytePtr = [myData mutableBytes];

for(int i = 0; i < [myData length]; i++) {
    bytePtr[i] += 0x01;
}

NSLog(@"%@", myData);

There's more info in the Binary Data Programming Guide article, "Working With Mutable Binary Data".

Also, what you're doing is not "shifting" but merely adding 0x01. "Shifting" typically refers to "bit shifting".

他のヒント

something like this:

NSString *_chars = @"abcd";
NSMutableData *_data = [NSMutableData dataWithBytes:[_chars UTF8String] length:_chars.length];

NSLog(@"Bef. : %@", _data);    
for (int i = 0; i < _data.length; i++) ((char *)[_data mutableBytes])[i]++;
NSLog(@"Aft. : %@", _data);    

the log shows the result:

Bef. : <61626364>
Aft. : <62636465>
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top