Timeline for Type to byte array conversion in Swift
Current License: CC BY-SA 3.0
12 events
when toggle format | what | by | license | comment | |
---|---|---|---|---|---|
Oct 30, 2016 at 8:28 | comment | added | DevAndArtist |
Hmm, forget about my last example. I run into that problem I mentioned yesterday, because in my codebase I'm reusing the global generic function that converts T to [Byte] . It seems like from within an extension we're getting the correct size of Self . swiftlang.ng.bluemix.net/#/repl/5815aec90a78bb5651913186 At the bottom when I just the bare function you'll see the wrong result I meant. Sorry for confusion.
|
|
Oct 30, 2016 at 7:59 | comment | added | Martin R |
@DevAndArtist: Sorry, but I cannot reproduce. ([1, 0.5, UInt16(0x1234), Float(0.5)] as [PackableType]).map { $0.pack(byteOrder: .LittleEndian) } gives [[1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 224, 63], [52, 18], [0, 0, 0, 63]] with above code. Am I missing something?
|
|
Oct 30, 2016 at 6:08 | comment | added | DevAndArtist |
That's correct but if you'd try ([1, 0.5] as [PackageType]).map { $0.pack(byteOrder: .littleEndian) } you'll get an array of two arrays of bytes, but these two array will be 40 bytes long each. The result is clearly not what you'd expect ;)
|
|
Oct 29, 2016 at 22:27 | comment | added | Martin R |
@DevAndArtist: Thank you for the feedback. Note that conformance to PackableType is (intentionally) declared explicitly for all "simple" types (like integers and floating point values) which can safely be byte-copied to an array and back. You cannot call the pack method on UInt8(0) as Any .
|
|
Oct 29, 2016 at 20:28 | comment | added | DevAndArtist |
There is one dangerous thing you should change. sizeofValue(value) (which is now MemoryLayout.size(ofValue:) ) should be MemoryLayout<Self>.size . The thing is, if you cast to PackableType and execute pack(byteOrder:) you'll get a wrong result. For instance MemoryLayout.size(ofValue: UInt8(0) as Any) is 32 bytes instead of what you would expect.
|
|
Dec 22, 2015 at 18:26 | vote | accept | Michael Dorner | ||
Dec 22, 2015 at 12:31 | history | edited | Martin R | CC BY-SA 3.0 |
added 2265 characters in body
|
Dec 22, 2015 at 12:01 | history | edited | Martin R | CC BY-SA 3.0 |
typo
|
Dec 22, 2015 at 11:14 | history | edited | Martin R | CC BY-SA 3.0 |
added 54 characters in body
|
Dec 22, 2015 at 11:06 | history | edited | Martin R | CC BY-SA 3.0 |
added 1367 characters in body
|
Dec 22, 2015 at 10:47 | history | edited | Martin R | CC BY-SA 3.0 |
added 477 characters in body
|
Dec 22, 2015 at 10:40 | history | answered | Martin R | CC BY-SA 3.0 |