如何在Swift中编写Java字节数组

时间:2017-11-05 14:58:24

标签: java arrays swift byte

我试图在Swift中编写以下Java代码:

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' };

如何做到这一点?

1 个答案:

答案 0 :(得分:5)

您可以简单地将这些字符添加到String中,并使用该字符串utf8属性从中初始化新的字节数组。结果将是一个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也符合RandomAccessCollectionMutableCollectionRangeReplaceableCollection,因此您只需使用Data代替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"