Update for Swift 3/Xcode 8:

String from bytes: [UInt8]:

if let string = String(bytes: bytes, encoding: .utf8) {
    print(string)
} else {
    print("not a valid UTF-8 sequence")
}

String from data: Data:

let data: Data = ...
if let string = String(data: data, encoding: .utf8) {
    print(string)
} else {
    print("not a valid UTF-8 sequence")
}

Update for Swift 2/Xcode 7:

String from bytes: [UInt8]:

if let string = String(bytes: bytes, encoding: NSUTF8StringEncoding) {
    print(string)
} else {
    print("not a valid UTF-8 sequence")
}

String from data: NSData:

let data: NSData = ...
if let str = String(data: data, encoding: NSUTF8StringEncoding) {
    print(str)
} else {
    print("not a valid UTF-8 sequence")
}

Previous answer:

String does not have a stringWithBytes() method. NSString has a

 NSString(bytes: , length: , encoding: )

method which you could use, but you can create the string directly from NSData, without the need for an UInt8 array:

if let str = NSString(data: data, encoding: NSUTF8StringEncoding) as? String {
    println(str)
} else {
    println("not a valid UTF-8 sequence")
}
Answer from Martin R on Stack Overflow
🌐
GitHub
github.com › vapor › core › blob › main › Sources › Bits › ByteBuffer+string.swift
core/Sources/Bits/ByteBuffer+string.swift at main · vapor/core
/// Reads a null-terminated `String` from this `ByteBuffer`. /// /// - parameters: /// - encoding: `String.Encoding` to use when converting the bytes to a `String` public mutating func readNullTerminatedString(encoding: String.Encoding = .utf8) -> String?
Author: vapor
Discussions

Reading invalid strings from ByteBuffer - SwiftNIO - Swift Forums
I noticed that the ByteBuffer for reading strings are not fallible. This means that I can create an invalid string like so: let invalidUTF8 = context.channel.allocator.buffer(bytes: [0xc3, 0x28]) let invalidString = String(buffer: invalidUTF8) Creating a String directly from the array of bytes ... More on forums.swift.org
🌐 forums.swift.org
0
May 6, 2021
How to convert String to byte in Swift? - Stack Overflow
How to convert String to byte in Swift? Like String .getBytes()in Java. More on stackoverflow.com
🌐 stackoverflow.com
Converting Binary String back to original string using Swift
With your code, the Result output contains line break characters at each end of the binary string, so I used this String as Result outpuut. Using resultOutput, you can write something like this: By the way, your code can be shortened utilizing the functionality of Swift and Swift Standard Library. More on developer.apple.com
🌐 developer.apple.com
Use JSONDecoder with ByteBuffer - Using Swift - Swift Forums
Hi, I'm currently working on a TCP server using SwiftNIO, and I can't find an easy way to convert a ByteBuffer directly to Data in order to decode it more easily. Here is my inbound handler tasked with parsing the received messages: final class MessageParser: ChannelInboundHandler { typealias ... More on forums.swift.org
🌐 forums.swift.org
1
November 22, 2020
🌐
Apple Developer
developer.apple.com › documentation › swift › string › init(bytes:encoding:)
init(bytes:encoding:) | Apple Developer Documentation
Creates a new string equivalent to the given bytes interpreted in the specified encoding. Note: This API does not interpret embedded nulls as termination of the string. Use String?(validatingCString:) instead for null-terminated C strings.
🌐
Swift Forums
forums.swift.org › related projects › swiftnio
Reading invalid strings from ByteBuffer - SwiftNIO - Swift Forums
May 6, 2021 - This means that I can create an invalid string like so: let invalidUTF8 = context.channel.allocator.buffer(bytes: [0xc3, 0x28]) let invalidString = String(buffer: invalidUTF8) Creating a String directly from the array of bytes ...
🌐
Dot Net Perls
dotnetperls.com › convert-string-byte-array-swift
Swift - Convert String to Byte Array - Dot Net Perls
September 17, 2024 - It is possible to create a String from a sequence of bytes. We can specify these directly in the program.
🌐
Swift Package Index
swiftpackageindex.com › apple › swift-nio › main › documentation › NIOCore › ByteBuffer
swift-nio Documentation – Swift Package Index
This page requires JavaScript · Please turn on JavaScript in your browser and refresh the page to view its content · Last updated on 25 Jun 2026
Find elsewhere
🌐
Apple Developer
developer.apple.com › forums › thread › 660595
Converting Binary String back to original string using Swift
With your code, the Result output contains line break characters at each end of the binary string, so I used this String as Result outpuut. Using resultOutput, you can write something like this: By the way, your code can be shortened utilizing the functionality of Swift and Swift Standard Library.
🌐
Fossies
fossies.org › linux › flatbuffers › swift › Sources › FlatBuffers › ByteBuffer.swift
FlatBuffers: swift/Sources/FlatBuffers/ByteBuffer.swift | Fossies
447 func withUnsafeMutableRawPointer<T>( 448 body: (UnsafeMutableRawPointer) throws 449 -> T) rethrows -> T 450 { 451 try _storage.withUnsafeRawPointer(body) 452 } 453 454 @discardableResult 455 @inline(__always) 456 func readWithUnsafeRawPointer<T>( 457 position: Int, 458 _ body: (UnsafeRawPointer) throws -> T) rethrows -> T 459 { 460 try _storage.readWithUnsafeRawPointer(position: position, body) 461 } 462 } 463 464 extension ByteBuffer: CustomDebugStringConvertible { 465 466 public var debugDescription: String { 467 """ 468 buffer located at: \(_storage.retainedBlob), 469 with capacity of \(capacity), 470 { writtenSize: \(_readerIndex), readerSize: \(reader), 471 size: \(size) } 472 """ 473 } 474 }
🌐
GitHub
gist.github.com › lzell › c0747a18742ca2dd59bfb969ce35e768
Swift string to data (bytes) and back · GitHub
Swift string to data (bytes) and back · Raw · string_to_data_back.swift · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
🌐
Swift Forums
forums.swift.org › using swift
Use JSONDecoder with ByteBuffer - Using Swift - Swift Forums
November 22, 2020 - Hi, I'm currently working on a TCP server using SwiftNIO, and I can't find an easy way to convert a ByteBuffer directly to Data in order to decode it more easily. Here is my inbound handler tasked with parsing the received messages: final class MessageParser: ChannelInboundHandler { typealias InboundIn = ByteBuffer typealias InboundOut = CommsMessage public func channelRead(context: ChannelHandlerContext, data: NIOAny) { do { var buffer = self.unwrapInboundI...
🌐
Swift Package Index
swiftpackageindex.com › apple › swift-nio › 2.80.0 › documentation › niocore › bytebuffer
ByteBuffer | Documentation - Swift Package Index
January 28, 2025 - This page requires JavaScript · Please turn on JavaScript in your browser and refresh the page to view its content · Last updated on 28 Jan 2025
🌐
Swift Forums
forums.swift.org › using swift
Swift NIO: noob question about reading all bytes - Using Swift - Swift Forums
June 15, 2019 - Out of curiosity I'm trying to build a simple socket client using Swift NIO. What I want to do is simply to send a message to the server, get the response and close the connection. The server to which I'm connecting (I do not have access to its source code) writes back a response of 4152 bytes, in chunks of maximum 1024 bytes each.
🌐
Swift Forums
forums.swift.org › using swift
How to convert String to byte array? - Using Swift - Swift Forums
March 8, 2022 - I would like to take a String: let myStr = "This is a string" And take the first n bytes from it: let firstNBytes = ... I'm not even sure what data type holds bytes in Swift, Data? UInt8?
Top answer
1 of 1
2

I believe the object you are looking for is Data. It is an object that can represent any data and holds raw byte buffer.

For your specific case you need to convert array of double values to data which can be done like this:

let data: Data = doubleArray.withUnsafeBufferPointer { Data(buffer: $0) }

Now to get the hex string from Data I suggest you reference some other post.

Adding this answer code you should be able to construct your hex string by doing

let hexString = data.hexEncodedString()

So to put it ALL together you would do:

extension Data {
    struct HexEncodingOptions: OptionSet {
        let rawValue: Int
        static let upperCase = HexEncodingOptions(rawValue: 1 << 0)
    }

    func hexEncodedString(options: HexEncodingOptions = []) -> String {
        let format = options.contains(.upperCase) ? "%02hhX" : "%02hhx"
        return map { String(format: format, $0) }.joined()
    }
}

func generateRandomDoubleBufferHexString(count: Int, randomParameters: (min: Double, max: Double, percision: Int) = (0.0, 1.0, 100000)) -> String {

    func generateRandomDouble(min: Double = 0.0, max: Double = 1.0, percision: Int = 100000) -> Double {
        let scale: Double = Double(Int(arc4random())%percision)/Double(percision)
        return min + (max-min)*scale
    }

    var doubleArray: [Double] = Double // Create empty array
    // Fill array with random values
    for _ in 0..<count {
        doubleArray.append(generateRandomDouble(min: randomParameters.min, max: randomParameters.max, percision: randomParameters.percision))
    }

    // Convert to data:
    let data: Data = doubleArray.withUnsafeBufferPointer { Data(buffer: $0) }

    // Convert to hex string
    return data.hexEncodedString()
}
🌐
GitHub
github.com › apple › swift-nio › issues › 253
`ByteBuffer.set(string:)` returns an `Optional` Int · Issue #253 · apple/swift-nio
March 28, 2018 - Int The set(string:at:) (and write(string:)) return an Optional even though they never fail (looking at the implemen...
Author: apple