//
//  NSData+CustomDescription.m
//  iOSPrinterDemo
//
//  Created by ldc on 2017/9/23.
//  Copyright © 2017年 Mellow. All rights reserved.
//

#import "NSData+CommandConvert.h"

@implementation NSData (CommandConvert)

- (NSString *)hexString {
    
    NSMutableString *mStr = [NSMutableString new];
    for (int i = 0; i < self.length; i++) {
        Byte a;
        [self getBytes:&a range:NSMakeRange(i, 1)];
        NSString *temp = [NSString stringWithFormat:@"%02x",a];
        [mStr appendString:temp];
    }
    return mStr;
}

+ (NSData *)dataWithHexString:(NSString *)str {
    
    if (str.length%2 != 0) {
        return nil;
    }
    NSMutableData *mData = [NSMutableData new];
    for (int i = 0; i < str.length; i = i + 2) {
        
        NSString *subStr = [str substringWithRange:NSMakeRange(i, 2)];
        u_int8_t a;
        [[NSScanner scannerWithString:subStr] scanHexInt:&a];
        [mData appendBytes:&a length:1];
    }
    return mData;
}

@end
