UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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
            print(systemID)
        } else {
            print("Invalid string")
            systemID = "---"
        }

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

Any clues?

2      

Does something like this work for you?

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

2      

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
            print(systemID)
        } else {
            print("Invalid string")
            systemID = "---"
        }

But got error

Type of expression is ambiguous without more context

2      

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

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

2      

That works. Thank you very much.

2      

@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 👍

2      

Thanks for the reminder. Marked as solved.

2      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.