//
//  HexUtil.m
//  BTReader
//
//  Created by TZ on 15/10/13.
//  Copyright © 2015年 sunrise. All rights reserved.
//

#import "SRHexUtil.h"

@implementation SRHexUtil

/**
 功能：将16进制字符串转换成字节数组
 参数：16进制字符串
 结果：结果字节数组生成的NSData
 */
+(NSData*)hexStringToByte:(NSString*)string{
    NSString *hexString=[[string uppercaseString] stringByReplacingOccurrencesOfString:@" " withString:@""];
    if ([hexString length]%2!=0) {
        return nil;
    }
    Byte tempbyt[1]={0};
    NSMutableData* bytes=[NSMutableData data];
    for(int i=0;i<[hexString length];i++)
    {
        unichar hex_char1 = [hexString characterAtIndex:i]; ////两位16进制数中的第一位(高位*16)
        int int_ch1;
        if(hex_char1 >= '0' && hex_char1 <='9')
            int_ch1 = (hex_char1-48)*16;   //// 0 的Ascll - 48
        else if(hex_char1 >= 'A' && hex_char1 <='F')
            int_ch1 = (hex_char1-55)*16; //// A 的Ascll - 65
        else
            return nil;
        i++;
        
        unichar hex_char2 = [hexString characterAtIndex:i]; ///两位16进制数中的第二位(低位)
        int int_ch2;
        if(hex_char2 >= '0' && hex_char2 <='9')
            int_ch2 = (hex_char2-48); //// 0 的Ascll - 48
        else if(hex_char2 >= 'A' && hex_char2 <='F')
            int_ch2 = hex_char2-55; //// A 的Ascll - 65
        else
            return nil;
        
        tempbyt[0] = int_ch1+int_ch2;  ///将转化后的数放入Byte数组里
        [bytes appendBytes:tempbyt length:1];
    }
    return bytes;
}

/**
 功能：字节数组转16进制字符串
 参赛：字节数组 长度
 结果：16进制字符串
 */
+ (NSString *)bytesToHexString:(uint8_t *)bytes offset:(int)offset length:(int)length{
//    uint8_t bs[sizeof(bytes)];
//    [bytes getBytes:bs];
    NSString *hexString=[[NSString alloc] init];
    
    for (int i=offset; i<length; i++) {
        hexString=[hexString stringByAppendingString:[NSString stringWithFormat:@"%02x",bytes[i]]];
    }
    
    return hexString;
}

@end
