// // Utils.m // ActsBluetoothOTA // // Created by inidhu on 2019/5/22. // Copyright © 2019 Actions. All rights reserved. // #import "Utils.h" @implementation Utils + (UInt32)bytes2UInt32:(Byte*)bytes index:(NSInteger)index { return (((bytes[index + 3] & 0xFF) << 24) + ((bytes[index + 2] & 0xFF) << 16)) + ((bytes[index + 1] & 0xFF) << 8) + (bytes[index] & 0xFF); } + (UInt16)bytes2Short:(Byte*)bytes index:(NSInteger)index { return ((bytes[index + 1] & 0xFF) << 8) + (bytes[index] & 0xFF); } /* 计算0比特位的个数 */ + (NSInteger)countZeroBit:(NSData *) bitmap { NSInteger count = 0; Byte *bytes = (Byte *)[bitmap bytes]; NSInteger length = bitmap.length; for (int i = 0; i < length; i++ ) { Byte x = bytes[i]; while ((x + 1) != 0) { x |= (x + 1); count++; } } return count; } /* 从bitmap获取相应0bit位的索引 */ + (NSArray *)getZeroBitIndexMap:(NSData *) bitmap groupNum:(int) groupNum{ NSMutableArray *indexMap = [[NSMutableArray alloc] init]; NSInteger count = 0; NSInteger index = 0; Byte *bytes = (Byte *)[bitmap bytes]; for (NSInteger i = 0; i < bitmap.length; i++) { Byte b = bytes[i]; for (NSInteger j = 0; j < groupNum; j++) { int offset = (index % groupNum); if ((b & (0x1 << offset)) == 0x0) { [indexMap addObject:[NSNumber numberWithInteger:index]]; count++; } index++; } } return indexMap; } + (int32_t)crc32:(NSData *)data { uint32_t *table = malloc(sizeof(uint32_t) * 256); uint32_t crc = 0xffffffff; uint8_t *bytes = (uint8_t *)[data bytes]; for (uint32_t i=0; i<256; i++) { table[i] = i; for (int j=0; j<8; j++) { if (table[i] & 1) { table[i] = (table[i] >>= 1) ^ 0xedb88320; } else { table[i] >>= 1; } } } for (int i=0; i> 8) ^ table[crc & 0xff ^ bytes[i]]; } crc ^= 0xffffffff; free(table); return crc; } @end