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      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

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.