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      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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.