NEW: Start my new Ultimate Portfolio App course with a free Hacking with Swift+ trial! >>

SOLVED: String Formatting of Hex Data

Forums > Swift

I have a Data buffer containg 8 bit data. I'd like to format a String to represent this.

The data is typically

b4, a4, 34, f1, 00, 00, 29, bb, 58

I'd like a String formatted b4:a4:34:f1:00:00:29:bb:58

Apprciate I can insert colons after.

if let sysID = String(bytes: data, encoding: .utf8) {
             systemID = sysID
        } else {
            print("Invalid string")
            systemID = "---"

But comes back with invalid string. I guess not every character is displyeable.

Any clues?


Does something like this work for you?

let hexes = { String(format: "%02X", $0) }
print(hexes.joined(separator: ":"))


Thank you that seems to print the format I need. How would I assign it to String variable.

I tried

 if let sysID = String(bytes: hexes, encoding: .ascii) {
             systemID = sysID
        } else {
            print("Invalid string")
            systemID = "---"

But got error

Type of expression is ambiguous without more context


hexes.joined(separator: ":") returns a String, so you just have to assign it.

For instance: let hexStr = hexes.joined(separator: ":")


That works. Thank you very much.


@twostraws  Site AdminHWS+

Please remember to mark answers as solved if you can – it helps identify them for folks who come across this thread later on 👍


Thanks for the reminder. Marked as solved.


Hacking with Swift is sponsored by RevenueCat

SPONSORED Building and maintaining in-app subscription infrastructure is hard. Luckily there's a better way. With RevenueCat, you can implement subscriptions for your app in hours, not months, so you can get back to building your app.

Try it for free

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.