//
//  AlgorithmTool.m
//  OYGameSKD
//
//  Created by leon on 2021/4/27.
//  Copyright © 2021 Oujia. All rights reserved.
//

#import "AlgorithmTool.h"

@implementation AlgorithmTool
 //优先计算校验位--无误再进行数据处理  数据前面所有字节数相加是否等于最后一位
+(BOOL)verificationRusult:(NSData*)characteristicValue{

       if (characteristicValue.length<4){
            NSLog(@"无效报文");
            return NO;
       }
    
       NSData * frontData = [characteristicValue subdataWithRange:NSMakeRange(0, characteristicValue.length-1)];
       NSData * behindData = [characteristicValue subdataWithRange:NSMakeRange(characteristicValue.length-1, 1)];

       Byte  frontBytes = [self byteSumBBC:frontData];
       Byte  behindByte = [self byteSumBBC:behindData];

        if (frontBytes == behindByte){//校验位计算结果
            return YES;
        }else{
            NSLog(@"计算校验位出错");
            return NO;
        }

}

//测试
+ (Byte)bbcByte:(Byte *)bytes{
    
    Byte bcc = 0;
    NSInteger byteLength = sizeof(bytes);

    for (int i = 0; i < byteLength; i++){
        bcc += bytes[i];
    }
    return bcc;
    
}

//bbc
+ (Byte)byteSumBBC:(NSData *)data{

    Byte bcc = 0;
    if (data.length == 0){
        return bcc;
    }
    Byte *bytes = (Byte *)[data bytes];
    for (int i = 0; i < data.length; i++){
        bcc += bytes[i];
//        UInt8  ins = bytes[i];
//        NSLog(@"bytes[i] = %x",bytes[i]);
//        NSLog(@"bcc = %x",bcc);
    }
//    NSLog(@"bccTotavttelValue = %x",bcc);
    return bcc;

}

//Data To Char：返回1Byte的char数据 只有一个字节不会数据溢出 不用大小端转换
+ (char)dataToChar:(NSData *)data{

    char b = 0;
    //1个字节
   [data getBytes:&b length:data.length];
   return b;
    
}

//Data To Short：返回2Byte的short数据  数据溢出要大小端转换
+(short)dataToSwapBigShortToHost:(NSData*)data andRange:(NSRange)range{

  //两个字节
  short a = 0;
  [data getBytes:&a range:range];
  a = NSSwapBigShortToHost(a);
  return a;

}

//Data To Int：返回 不定个数 Byte的int数据
+(int)dataToInt:(NSData*)data{
    
   //2或4个字节
  int a = 0;
  [data getBytes:&a length:data.length];
  return a;
    
}

//Data To Int：返回 不定个数 Byte的int数据 数据溢出要大小端转换
+(int)dataToSwapBigIntToHost:(NSData*)data andRange:(NSRange)range{
    
   //四个字节
  int a = 0;
  [data getBytes:&a range:range];
  a = NSSwapBigIntToHost(a);
  return a;
    
}

/**
十六进制数据流转字符串
*/
+(NSString *)hexadecimalString:(NSData *)data{

    NSString *result;
    const unsigned char *dataBuffer = (const unsigned char *)[data bytes];
    if (!dataBuffer) {
        return nil;
    }
    NSUInteger dataLength = [data length];
    NSMutableString *hexString = [NSMutableString stringWithCapacity:(dataLength * 2)];
    for (int i = 0; i<dataLength; i++) {
        //02x 表示两个位置 显示的16进制
        [hexString appendString:[NSString stringWithFormat:@"%02lx",(unsigned long)dataBuffer[i]]];
    }
    result = [NSString stringWithString:hexString];
    return result;

}

/**
  字符串转16进制NSData数据流
*/
+(NSData *)convertHexStrToData:(NSString *)str{

    if (!str || [str length] == 0){
        return nil;
    }
    NSMutableData *hexData = [[NSMutableData alloc] initWithCapacity:20];
    NSRange range;
    if ([str length] % 2 == 0) {
        range = NSMakeRange(0, 2);
    } else {
        range = NSMakeRange(0, 1);
    }
    for (NSInteger i = range.location; i < [str length]; i += 2){

        unsigned int anInt;
        NSString *hexCharStr = [str substringWithRange:range];

        NSScanner *scanner = [[NSScanner alloc] initWithString:hexCharStr];

//        NSLog(@"字符串转16进制数据流 scanner: %@", scanner);

        [scanner scanHexInt:&anInt];

        NSData *entity = [[NSData alloc] initWithBytes:&anInt length:1];

        [hexData appendData:entity];

        range.location += range.length;
        range.length = 2;

    }

//    NSLog(@"字符串转16进制数据流 hexdata: %@", hexData);
    return hexData;

}

//json字符串转字典
+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString{
    
    if (jsonString == nil){
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
    if(err){
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
    
}





// 返回时间戳 精确到毫秒
+ (NSString *)returnTimestamp{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss SSS"]; // 设置想要的格式，hh与HH的区别:分别表示12小时制,24小时制
    //设置时区,这一点对时间的处理有时很重要
    NSTimeZone*timeZone=[NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [formatter setTimeZone:timeZone];
    NSDate *datenow = [NSDate date];
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]*1000];
    NSLog(@"时间戳  ===>> %@",timeSp);
    return timeSp;
    
}

@end
