如何在Swift中编写Java字节数组 [英] How to write Java byte array in Swift
本文介绍了如何在Swift中编写Java字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在Swift中编写以下Java代码:
I'm trying to write the following Java code in Swift:
private static final byte[] ENCRYPTION_KEY = new byte[] { 'N', 'r', 'q', 'V', '2', 'h', 'V', 'j', 'z', 'D', 'N', 'p', 'V', 'T', '3', 'X' };
private static final byte[] VECTOR = new byte[] { 'f', 'e', 'l', 'c', 'd', 'a', '1', '8', '7', '2', '5', '4', '3', '2', '8', '0' };
这怎么办?
推荐答案
您可以简单地将这些字符添加到字符串中,然后使用该字符串utf8属性从中初始化一个新的字节数组。结果将是UInt8 [UInt8]
的数组:
You can simply add those characters into a String and use that string utf8 property to initialize a new array of bytes from it. The result will be an array of UInt8 [UInt8]
:
let encryptionKey = Array("NrqV2hVjzDNpVT3X".utf8) // [78, 114, 113, 86, 50, 104, 86, 106, 122, 68, 78, 112, 86, 84, 51, 88]
let vector = Array("felcda1872543280".utf8) // [102, 101, 108, 99, 100, 97, 49, 56, 55, 50, 53, 52, 51, 50, 56, 48]
请注意,由于Swift3 Data
也符合 RandomAccessCollection
, MutableCollection
和 RangeReplaceableCollection
,因此您只需使用数据
而不是 Array
:
Note that since Swift3 Data
also conforms to RandomAccessCollection
, MutableCollection
and RangeReplaceableCollection
so you could simply use Data
instead of Array
:
let encryptionKey = Data("NrqV2hVjzDNpVT3X".utf8) // 16 bytes
let vector = Data("felcda1872543280".utf8) // 16 bytes
encryptionKey[0] // 78
vector[0] // 102
print(Array(encryptionKey)) // "[78, 114, 113, 86, 50, 104, 86, 106, 122, 68, 78, 112, 86, 84, 51, 88]\n"
print(Array(vector)) // "[102, 101, 108, 99, 100, 97, 49, 56, 55, 50, 53, 52, 51, 50, 56, 48]\n"
这篇关于如何在Swift中编写Java字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文