Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Int to UInt32 in Swift

Im making a Tcp client and therefore using the CFStreamCreatePairWithSocketToHost which is expecting an UInt32 for the second parameter.

Here is a sample of what I'm trying to do.:

func initNetwork(IP: String, Port: Int) {
    // relevant stuff

    //Convert Port:Int to UInt32 to make this shit work!

    CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, IP as NSString , Port , &readStream, &writeStream)

    // Irelevant stuff
}

I have been looking around for a solution for some time now, and i can't seem to find one!

like image 208
Mads Gadeberg Avatar asked Aug 30 '14 07:08

Mads Gadeberg


People also ask

What is UInt32 in Swift?

A 32-bit unsigned integer value type.

What is UInt32?

The UInt32 value type represents unsigned integers with values ranging from 0 to 4,294,967,295. UInt32 provides methods to compare instances of this type, convert the value of an instance to its String representation, and convert the String representation of a number to an instance of this type.


2 Answers

You can do it easily:

var x = UInt32(yourInt)
like image 67
Nikos M. Avatar answered Oct 22 '22 02:10

Nikos M.


Nikos M.'s answer might overflow because Swift Ints are 64 bit now, and Swift will crash when the default UInt32 initializer overflows. If you want to avoid overflow, use the truncatingBitPattern initializer.

If you're sure your data won't overflow, then you should use the default initializer because an overflow represents invalid data for your application. If you're sure your data will overflow, but you don't care about truncation (like if you're building hash values or something) then you probably want to truncate.

let myInt: Int = 576460752303423504
let myUInt32 = UInt32(truncatingBitPattern: myInt)
like image 18
Heath Borders Avatar answered Oct 22 '22 02:10

Heath Borders