简体   繁体   中英

How to append 3 bytes '110' at the end of NSMutableData

HERE IS THE CODE->

NSString* message = @"username,password";
NSMutableData *data = [[NSMutableData alloc] initWithData:
                       [message dataUsingEncoding:NSASCIIStringEncoding]];

[data appendBytes:"0x1""0x1""0x0"
               length:3];

I am expecting output -> username,password110

but not getting this.

What you are appending is not bytes, it's a string "0x10x10x0" . The first three characters get appended - specifically, '0' , 'x' , and '1' .

To append three bytes, create a byte array, and append it:

unsigned char suffixBytes[] = {1, 1, 0};
[data appendBytes:suffixBytes length:3];

In one specific case, when all bytes represent character codes of printable characters, you can use a string literal instead:

[data appendBytes:"110" length:3];

This will append character codes of '1' , '1' , and '0' to your data. Assuming ASCII encoding, the values would be {0x31, 0x31, 0x30} .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM