Extract Integers From Binary Based… | Apple Developer Forums

Có thể bạn quan tâm

Hello.

I have an array of bytes, e.g.

let arrayToCheck1 : [UInt8] = [0x47,0x52,0x49,0x42,0x0,0x0,0x0,0x2,0x0,0x0,0x0,0x0,0x0,0x0,0x81,0x35]

I have to extract an array of Integers from arrayToCheck1 where each integer is represented by a certain number of bits. For example, if the number of bits is 5, my values will be like this:

01000 11101 01001 00100 10010 10000 etc.

I.e., the whole array of bytes will be transfered into the following:

[8, 29, 9, 4, 18, 16, 16, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 1, 6]

I do this by implementing the following code:

// Method to convert an arry of bytes into an array of integers based on number of bits for one integer static func getValuesArrayFromBits(bytes byteArray:[UInt8], width fieldWidth:Int, totalBits bits:Int) -> [Int64] { // Convert the array of bytes into a binary string let convertedString = byteArrayToBinaryString(bytes: byteArray); // Convert the binary string into an arry of integers let finalResult = bitString2Ints(from: convertedString, width: fieldWidth, totalBits: bits) return finalResult; } // Converts an array of bytes to a String. static func byteArrayToBinaryString(bytes byteArray:[UInt8]) -> String { var arrayOfStrings = [String]() for i in 0..<byteArray.count { arrayOfStrings.append(byteToBinaryString(byte: byteArray[i])); } var bitsetString = "" for stringElement in arrayOfStrings { bitsetString += stringElement; } return bitsetString; } // Converts one byte to a binary string. static func byteToBinaryString(byte byteIn:UInt8) -> String { var sb = "00000000" func replace(myString: String, _ index: UInt8, _ newChar: Character) -> String { var chars = Array(myString.characters) / chars[Int(index)] = newChar let modifiedString = String(chars) return modifiedString } let bits : [UInt8] = [0,1,2,3,4,5,6,7] for bit in bits { if (((byteIn >> bit) & 1) > 0) { sb = replace(myString: sb, (7 - bit), "1") } } return sb; } // Convert the binary string into an arry of integers static func bitString2Ints(from binaryString : String, width bitWidth:Int, totalBits bits:Int) -> [Int64] { var finalArrayList = [Int64](repeating: 0, count: (bits/bitWidth)) if(binaryString.characters.count < bits) { let errorMessage = "Error!" print(errorMessage) finalArrayList[0] = -1; } else { var counterIndex = 0; for i in stride(from: 0, to: bits, by: bitWidth) { let binarySubstring = binaryString.substring(index: i, length: bitWidth) finalArrayList[counterIndex] = Int64(strtoul(binarySubstring, nil, 2)) counterIndex += 1 } } return finalArrayList; }

The code works. However, the problem is that it is VERY slow when I have an array of, for example, 30000 and more bytes.

Is there a more efficient way to extract integers from binary data based on a certain number of bits used for each integer?

Thanks a lot!

Từ khóa » C = 0x0 && C 0x81