简体   繁体   中英

How to write Java byte array in Swift

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

How can this be done?

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]

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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