Convert between hex, strings, and Data in Swift
How Swift hex, String, and Data conversions change stored bytes, when they stay usable, and when plain text is the better form.
Is this transformation suitable for my intended use?
Hex conversion is suitable when you need a printable, copyable stand-in for raw bytes: cryptographic material, protocol payloads, file contents, or debug dumps that must travel through String APIs. The main benefit is a lossless round trip of the byte sequence, provided the hex is well-formed and you do not also re-interpret those bytes as Unicode text. The decisive tradeoff is size and meaning: hex uses two ASCII characters per byte, so it is twice as large as Data and no longer reads as language. Keep the original String when the payload is prose, identifiers, or any text you still need to read, search, or edit as words. Use Data when an API consumes bytes. Use hex only for the text-only hop between those two.
- Prefer the original String when people must read the content as language.
- Prefer Data when you are hashing, encrypting, writing files, or talking to byte-oriented APIs.
- Prefer hex when those bytes must pass through logs, JSON strings, pasteboards, or other text-only channels.
- Treat “string to hex” and “hex string to Data” as different jobs: the first encodes text, the second parses digits.
What this conversion actually changes
These conversions change stored characters and bytes. They are not a font, a CSS effect, a mirrored glyph, a reversed reading order, or a bidirectional display trick. What you keep after conversion is a different sequence of values, not a restyled view of the same string.
| Form | What it holds | What conversion does |
| String | Unicode text | Choosing UTF-8 (the usual Swift path) encodes each scalar into one or more bytes. That is a text encoding step, not hex. |
| Data | An ordered buffer of bytes | No characters yet. Printing or logging Data is not the same as producing a hex string. |
| Hex string | ASCII digits 0-9 and letters a-f or A-F | Each byte becomes two hex characters. Parsing those pairs reconstructs the same bytes if the input is valid. |
A common mix-up is to treat a Swift String as if it were already bytes. “Hello” as UTF-8 is the five bytes 48 65 6c 6c 6f, which hex encodes as 48656c6c6f. That hex is a new String made of digit and letter characters. Parsing 48656c6c6f back to Data restores those five bytes. Decoding those bytes as UTF-8 restores “Hello”. Skipping the encoding step, or decoding with a different encoding, yields different Data or a failed String conversion.
Hex does not map one visible character to one unit. Combining marks and multi-code-point emoji first become several UTF-8 bytes, then each of those bytes becomes two hex digits. A flag emoji or a family-zwj sequence therefore expands into a long hex run. Reversing or mirroring that hex string would scramble bytes; this review is about encoding and parsing, not reversal. Letter case in hex (aa versus AA) is a stored-character difference. Parsers that accept both still recover the same bytes; the hex String itself is not identical.
Invalid hex is a hard failure, not a visual glitch. Odd length, whitespace you did not strip, and characters outside 0-9A-Fa-f do not correspond to bytes. A robust conversion either rejects that input or documents a specific cleanup rule (trim, drop a 0x prefix, ignore spaces). Silent truncation of a leftover nibble changes meaning.
Typical Swift conversions
The Foundation types involved are String and Data. UTF-8 is the usual bridge from text to bytes. Hex is then a separate map over those bytes. The snippets below use that split so the two transformations stay visible.
import Foundation
let text = "Hello"
let bytes = Data(text.utf8) // String → Data (UTF-8)
let hex = bytes.map { String(format: "%02x", $0) }.joined()
// hex == "48656c6c6f"
func data(fromHex hex: String) -> Data? {
let trimmed = hex.trimmingCharacters(in: .whitespacesAndNewlines)
guard trimmed.count.isMultiple(of: 2) else { return nil }
var out = Data(capacity: trimmed.count / 2)
var index = trimmed.startIndex
while index < trimmed.endIndex {
let next = trimmed.index(index, offsetBy: 2)
guard let byte = UInt8(trimmed[index..<next], radix: 16) else { return nil }
out.append(byte)
index = next
}
return out
}
let restored = data(fromHex: hex).flatMap { String(data: $0, encoding: .utf8) }
// restored == Optional("Hello")
String to hex without an explicit encoding is incomplete: you must choose how characters become bytes, then hex-encode those bytes. Data(text.utf8) makes UTF-8 explicit. String(format: "%02x", byte) emits a two-digit lowercase pair per byte, which matches the usual expectation for a compact dump. Uppercase would use %02X. Neither format inserts spaces or a 0x prefix; add those only if a receiver requires them, and strip them before parse.
Printing Data as hex is a different request from relying on the default description. print(data) describes the value; it is not a stable, copy-ready hex dump. Building a string with %02x (or %02X) is the conversion you can paste, compare, and parse. Inserting a separator, such as a space every byte or every 16 bytes, helps people scan a dump and must be removed before converting back to Data.
func hexDump(_ data: Data, uppercase: Bool = false) -> String {
let format = uppercase ? "%02X" : "%02x"
return data.map { String(format: format, $0) }.joined()
}
func hexDumpSpaced(_ data: Data) -> String {
data.map { String(format: "%02x", $0) }.joined(separator: " ")
}
print(hexDump(Data("Hello".utf8))) // 48656c6c6f
print(hexDumpSpaced(Data("Hello".utf8))) // 48 65 6c 6c 6f
Will the result remain readable and usable after copying or sharing?
A hex string is plain ASCII. Copied text is the stored digits and letters, so pasteboards, diffs, JSON string fields, and ordinary editors keep the same sequence. Search matches those characters, not the original prose. That is usable for machine round trips and awkward for reading: 48656c6c6f does not look like Hello unless the reader decodes it.
Data is binary. Copying a debug print of Data is not a defined hex format. Recipients who paste that description into a parser will fail unless the description happens to be only hex digits. Share an explicit hex string, or share the original text, rather than a runtime description.
Reading order does not reverse. Assistive technology will treat hex as a stream of letters and digits. Long dumps are tedious to hear and easy to mis-copy by a single nibble. This article does not include a scoped test of a named screen reader, browser, or editor, so compatibility claims stop at the character set: 0-9A-Fa-f plus any separators you added. Environments that normalize case, strip leading zeros, or reflow whitespace can still break a later parse even when the text remains visible.
Keep a plain-text equivalent whenever a person must understand the message. Hex is the transport form for bytes, not a replacement for the String those bytes came from. If the bytes were never valid UTF-8, there is no faithful String to keep; hex (or another binary-to-text mapping) is then the readable form you can share.
Gaps
- No measured timings, size ratios beyond the known two-characters-per-byte expansion, or app-specific API names are claimed here.
- Default print(Data) output is platform- and version-dependent; treat it as a debug description, not a specified hex encoding.
- Copy/paste and assistive-technology behavior is described from the character set and stored-text nature of hex, not from a documented test in a named destination.
- Whitespace, 0x prefixes, mixed case, and odd-length strings need an explicit policy in your parser; this review does not pick a library for you.