Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Int to UInt (and vice versa) bit casting in Swift

Tags:

I am looking for a direct way to bit cast the bit values of an Int to UInt and vice versa. For example (using the 8 bits integers for simplicity) I want to achieve the following:

let unsigned: UInt8 = toUInt8(-1)  // unsigned is 255 or 0xff let signed:   Int8  = toInt8(0xff) // signed is -1  

At first I came out with the following solution:

let unsigned = unsafeBitCast(Int8(-1), UInt8.self) let signed   = unsafeBitCast(UInt8(0xff), Int8.self) 

But Apple in the "unsafeBitCast()" documentation states the following:

.. Caution:: Breaks the guarantees of Swift's type system; use with extreme care. There's almost always a better way to do anything.

Does anyone have the better way?

like image 291
Michele Dall'Agata Avatar asked Nov 25 '14 12:11

Michele Dall'Agata


People also ask

How do I cast an int in Swift?

swift1min read To convert a float value to an Int, we can use the Int() constructor by passing a float value to it. Note: When we use this conversion the Integer is always rounded to the nearest downward value, like 12.752 to 12 or 6.99 to 6 .

What is int8 in Swift?

An 8-bit signed integer value type.

How many bits is an int in Swift?

Swift provides an additional integer type, Int , which has the same size as the current platform's native word size: On a 32-bit platform, Int is the same size as Int32 .


1 Answers

You can do:

let unsigned = UInt8(bitPattern: Int8(-1)) // -> 255 let signed   = Int8(bitPattern: UInt8(0xff)) // -> -1 

Many similar initializers exist:

extension Int8 {     init(_ v: UInt8)     init(_ v: UInt16)     init(truncatingBitPattern: UInt16)     init(_ v: Int16)     init(truncatingBitPattern: Int16)     init(_ v: UInt32)     init(truncatingBitPattern: UInt32)     init(_ v: Int32)     init(truncatingBitPattern: Int32)     init(_ v: UInt64)     init(truncatingBitPattern: UInt64)     init(_ v: Int64)     init(truncatingBitPattern: Int64)     init(_ v: UInt)     init(truncatingBitPattern: UInt)     init(_ v: Int)     init(truncatingBitPattern: Int)     init(bitPattern: UInt8) } 
like image 157
rintaro Avatar answered Oct 26 '22 05:10

rintaro