//
//  NSString+HexUtil.m
//  MyBluetoothTest
//
//  Created by Emmanuel Adeyemi on 1/8/16.
//  Copyright © 2016 Emmanuel Adeyemi. All rights reserved.
//

#import "NSString+HexUtil.h"

@implementation NSString (HexUtil)

-(NSData *)hexStringToData{
    
    const char *chars = [self UTF8String];
    long len = self.length;
    int i = 0;
    
    NSMutableData *data = [NSMutableData dataWithCapacity:len / 2];
    char byteChars[3] = {'\0','\0','\0'};
    unsigned long wholeByte;
    
    while (i < len) {
        byteChars[0] = chars[i++];
        byteChars[1] = chars[i++];
        wholeByte = strtoul(byteChars, NULL, 16);
        [data appendBytes:&wholeByte length:1];
    }
    
    return data;
}


-(NSData *)hexStringToData:(NSString *)delimiter{
    
    NSString *temp;
    temp = [self stringByReplacingOccurrencesOfString:delimiter withString:@""];
    
    return [temp hexStringToData];
    
}

-(NSData *)stringToData {
    
    NSMutableData *d=[NSMutableData data];
    
    NSString *temp;

    temp =[self lowercaseString];
    int count=0;
    uint8_t b=0;
    for(int i=0;i<self.length;i++)
    {
        b<<=4;
        char c=[temp characterAtIndex:i];
        if(c<'0' || (c>'9' && c<'a') || c>'f')
        {
            b=0;
            count=0;
            continue;
        }
        if(c>='0' && c<='9')
            b|=c-'0';
        else
            b|=c-'a'+10;
        count++;
        if(count==2)
        {
            [d appendBytes:&b length:1];
            b=0;
            count=0;
        }
    }
    
    return d;
}

+(NSString *)hexFromData : (NSData *) data{
    NSUInteger i, len;
    unsigned char *bytes;
    
    const unsigned char *buf = data.bytes;
    NSUInteger capacity = data.length * 2;
    NSMutableString *sbuf = [NSMutableString stringWithCapacity:capacity];
    len = data.length;
    bytes = (unsigned char*)data.bytes;
    buf = malloc(len*2);
    
    for (i=0; i<len; i++) {
        [sbuf appendFormat:@"%02lX", (unsigned long)buf[i]];
    }
    
    return sbuf;
}

+(NSString *)toHexString:(const void *)data
                  length:(size_t)length
                   space:(bool)space{
    
    const char HEX[]="0123456789ABCDEF";
    char s[2000];
    
    int len=0;
    for(int i=0;i<length;i++)
    {
        s[len++]=HEX[((uint8_t *)data)[i]>>4];
        s[len++]=HEX[((uint8_t *)data)[i]&0x0f];
        if(space)
            s[len++]=' ';
    }
    s[len]=0;
    return [NSString stringWithCString:s encoding:NSASCIIStringEncoding];
}



@end
