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
            print(systemID)
        } 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 = data.map { 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
            print(systemID)
        } 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 Instabug

SPONSORED Catch bugs as soon as they happen and know exactly why a crash occurred. Instabug's SDK grabs all the logs they need to fix bugs, crashes and performance issues in minutes instead of days. Get screenshots, device details, network logs, repro steps, and tons of other critical insights needed to resolve issues and prioritize product backlogs straight from your dashboard. It only takes a minute to integrate!

Get started now

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.