简体   繁体   中英

How to add padding to NSData so that it will be a multiple of 8 bytes?

In my code I construct a hex NSString first and then use the utility function below to convert it to NSData for transmission. For example:

+ (NSData *)convertHexString:(NSString *)hexString {
NSString *command = [hexString stringByReplacingOccurrencesOfString:@" " withString:@""];
NSMutableData *commandToSend = [[NSMutableData alloc] init];
unsigned char whole_byte;
char byte_chars[3] = { '\0', '\0', '\0' };
int i;
for (i = 0; i < [command length] / 2; i++) {
    byte_chars[0] = [command characterAtIndex:i * 2];
    byte_chars[1] = [command characterAtIndex:i * 2 + 1];
    whole_byte = strtol(byte_chars, NULL, 16);
    [commandToSend appendBytes:&whole_byte length:1];
}
return commandToSend;

}

Now there is a requirement that specifies "NSData must be a minimum of 8 bytes and be a multiple of 8 bytes. NULL padding can be used to make the data a multiple length of 8 bytes." I am not sure how I can make this happen.

NSString* hexString = @"FF88";//this is two bytes right now.
                              //how do I add NULL padding so that it becomes 8 bytes?

Thank you!

The code below will align on 16 bytes. You could easily change it to 8 bytes as also indicated in the comments, but, depending on what you are implementing, 16 bytes might be better nowadays.

    <whatever> * p;
    <whatever> * p16;

    // Unaligned pointer
    p = malloc ( n * sizeof ( <whatever> ) + 15 ); // use 7 for 8 byte alignment

    if ( p )
    {
        memset ( p, 0, n * sizeof ( <whatever> ) + 15 ); // 7 for 8 bytes

        // 16 byte aligned pointer
        p16 = ( ( uintptr_t ) p + 15 ) & ~ ( uintptr_t ) 0x0F; // 0x08 for 8 bytes

        // now p16 is aligned - use as is
    }
    // else allocation failed handle error

Change <whatever> to taste.

PS: This is more a general pointer alignment solution, not for NSString. So you'd use it if you convert it to a char * somewhere.

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