Utils.m
2.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
//
// 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<data.length; i++) {
crc = (crc >> 8) ^ table[crc & 0xff ^ bytes[i]];
}
crc ^= 0xffffffff;
free(table);
return crc;
}
@end