Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
591 views
in Technique[技术] by (71.8m points)

bitwise operators - Split UInt32 into [UInt8] in swift

I want to add UInt32 to byte buffer for which I use [UInt8]. In java, there is convenient ByteBuffer class that has methods like putInt() for cases exactly like this. How could this be done in swift?

I guess I could solve this as following:

let example: UInt32 = 72 << 24 | 66 << 16 | 1 << 8 | 15
var byteArray = [UInt8](count: 4, repeatedValue: 0)

for i in 0...3 {
    byteArray[i] = UInt8(0x0000FF & example >> UInt32((3 - i) * 8))
}

This is quite verbose though, any simpler way?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your loop can more compactly be written as

let byteArray = 24.stride(through: 0, by: -8).map {
    UInt8(truncatingBitPattern: example >> UInt32($0))
}

Alternatively, create an UnsafeBufferPointer and convert that to an array:

let example: UInt32 = 72 << 24 | 66 << 16 | 1 << 8 | 15

var bigEndian = example.bigEndian
let bytePtr = withUnsafePointer(&bigEndian) {
    UnsafeBufferPointer<UInt8>(start: UnsafePointer($0), count: sizeofValue(bigEndian))
}
let byteArray = Array(bytePtr)

print(byteArray) // [72, 66, 1, 15]

Update for Swift 3 (Xcode 8 beta 6):

var bigEndian = example.bigEndian
let count = MemoryLayout<UInt32>.size
let bytePtr = withUnsafePointer(to: &bigEndian) {
    $0.withMemoryRebound(to: UInt8.self, capacity: count) {
        UnsafeBufferPointer(start: $0, count: count)
    }
}
let byteArray = Array(bytePtr)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...