//
//  NSData+Hex.m
//  react_ios
//
//  Created by JohnnyChung on 2016/11/21.
//  Copyright © 2016年 Facebook. All rights reserved.
//

#import "NSData+Hex.h"

@implementation NSData(Hex)

- (NSString *) dataToHexString{
  
  const unsigned char *dataBuffer = (const unsigned char *)[self bytes];
  
  if (!dataBuffer)
    return [NSString string];
  
  NSUInteger dataLength  = [self length];
  NSMutableString *hexString  = [NSMutableString stringWithCapacity:(dataLength * 2)];
  
  for (int i = 0; i < dataLength; ++i){
    [hexString appendString:[NSString stringWithFormat:@"%02lX", (unsigned long)dataBuffer[i]]];
  }
  
  return [NSString stringWithString:hexString];
  
}

+ (NSData *)dataWithHexString:(NSString *)hexstring
{
  NSMutableData* data = [NSMutableData data];
  int idx;
  for (idx = 0; idx+2 <= hexstring.length; idx+=2) {
    NSRange range = NSMakeRange(idx, 2);
    NSString* hexStr = [hexstring substringWithRange:range];
    NSScanner* scanner = [NSScanner scannerWithString:hexStr];
    unsigned int intValue;
    [scanner scanHexInt:&intValue];
    [data appendBytes:&intValue length:1];
  }
  
  return data;
}


@end
