Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 3 - How to convert memory of Int32 as four characters

I want to convert an Int32 to a string consisting of four C-style, 1-byte wide characters (probably closely related to this but in Swift 3).

The use for this is that many API functions of Core Audio return an OSStatus (really an Int32), which can often be interpreted as string consisting of four C-style characters.

fun interpretAsString(possibleMsg: Int32) -> String {
  // Blackbox
}

1 Answers

Actually a "four character code" is usually an unsigned 32-bit value:

public typealias FourCharCode = UInt32
public typealias OSType = FourCharCode

The four bytes (from the MSB to the LSB) each define one character. Here is a simple Swift 3 function to convert the integer to a string, inspired by the various C/Objective-C/Swift 1+2 solutions in iOS/C: Convert "integer" into four character string:

func fourCCToString(_ value: FourCharCode) -> String {
    let utf16 = [
        UInt16((value >> 24) & 0xFF),
        UInt16((value >> 16) & 0xFF),
        UInt16((value >> 8) & 0xFF),
        UInt16((value & 0xFF)) ]
    return String(utf16CodeUnits: utf16, count: 4)
}

Example:

print(fourCCToString(0x48454C4F)) // HELO

I have chosen an array with the UTF-16 code points as intermediate storage because that can directly be used to create a string.

If you really need it for a signed 32-bit integer then you can call

fourCCToString(FourCharCode(bitPattern: i32value)

or define a similar function taking an Int32 parameter.

As Tim Vermeulen suggested below, the UTF-16 array can also be created with map:

let utf16 = stride(from: 24, through: 0, by: -8).map {
    UInt16((value >> $0) & 0xFF)
}

or

let utf16 = [24, 16, 8, 0].map { UInt16((value >> $0) & 0xFF) }

Unless the function is performance critical for your application, pick what you feel most familiar with (otherwise measure and compare).

like image 172
Martin R Avatar answered Sep 04 '25 23:09

Martin R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!