Faster way of converting image hex dump to binary array in Swift

521 Views Asked by At

I need to edit the pixels' raw binary values of an image. For this, I did this steps:

  1. I obtained the CFData containing the hex dump of the image.

  2. I converted the CFData obtained to an array of characters (using convertToArray function)

  3. After that, I used convertToBinaryString function to obtain a string representing the base 2 value of the hex dump.

It does work and does the job for small files but when it comes to bigger ones it takes forever to finish. I failed in the struggle of finding a faster way. Could you help me?

Down here you can take a look of the functions I need to optimize:

func convertToArray(imageData : CFData) -> Array<Character>{
  let arrayData : Array<Character> = Array(String(NSData(data: imageData)).characters)
  print("Array : ")
  Swift.print(arrayData)
  return arrayData
}

func convertToBinaryString(array : Array<Character>) -> String{
    let numberOfChars = array.count
    var binaryString = convertHexToBinary(array[1])
    for character in 2...numberOfChars - 2{
        binaryString = binaryString + convertHexToBinary(array[character])
    }
    // print("BINARRY ARRAY : ")
    // print(binaryString)
    return binaryString

}
1

There are 1 best solutions below

3
AudioBubble On

I would try this extension to NSData that provides a CollectionType interface. It seems like it would make it much easier for you to do your modifications without having to much around with UnsafeMutablePointer:

Bytes collection for NSData

Since BytesView and MutableBytesView are a CollectionType it gives you subscripting, indices, and more so you can iterate through your data and make the changes you want.

The article which is relevant to this question and introduces that linked code:

NSData, My Old Friend