简体   繁体   English

Swift-将图像数据转换为二进制数

[英]Swift - Convert an Image's Data to Binary Number

Is it possible to take an image and convert its data to Binary? 是否可以拍摄图像并将其数据转换为Binary?

I was able to convert an image's data to a String , but I'm not sure how to now take that String and display its Binary equivalent. 能够将图像数据转换为字符串 ,但我不知道现在该怎么采取串并显示等值的二进制数。

For that matter, if I type in a word - any word, like for example "Hello", I'd like the App to display the FIVE binary numbers that make it up: 为此,如果我输入一个单词- 任何单词,例如“ Hello”,我希望该应用程序显示组成它的5个二进制数字:
-the first number would be the binary number (or binary code) for the letter "H" -第一个数字是字母“ H”的二进制数(或二进制代码)
-the second number would be the binary number for the letter "e" -第二个数字是字母“ e”的二进制数字
-the third number would be the binary number for the letter "l" -第三个数字是字母“ l”的二进制数字

etc. 等等

You can get the binary data from a String like, 您可以像这样从String获取binary data

let str = "hello"
let data = str.data(using: .utf8)

In case you want to get the binary data in the form of 0/1, you can use, 如果您想要以0/1的形式获取二进制数据,可以使用,

data?.forEach({ print(String($0, radix: 2)) })

The above code prints the binary numbers corresponding to each byte in data . 上面的代码打印对应于data每个bytebinary numbers

Edit: 编辑:

To get 8 characters long binary numbers , you just need to append extra 0s to the start of the string , ie 要获得8 characters长的binary numbers ,您只需要在string的开头append extra 0s ,即

let binaryArr = data?.map({(byte) -> String in
    var str = String(byte, radix: 2)
    let countToAppend = 8 - str.count
    let extraZerosStr = ([String](repeating: "0", count: countToAppend)).joined()
    str = extraZerosStr + str
    return str
})

print(binaryArr) //for "Hello", it prints ["01001000", "01100101", "01101100", "01101100", "01101111"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM