1

I have seen several posts on how to covert and make a hex string, but the issue I am running into is when writing to file. I know how to create what I want as a utf8 string with proper spacing.

5350 4401 0000 0002 0500 0000 0000 0000 1540 0016 4000 5a80 005a 7000 5abc 0056 b000 5680 0056 8001 7fa0 017f a001 5fe0 0157 f00d 56bc 0d56 a001 56a0 0156 a003 56bc 00c0 c000 0000 8100 0001 00

The code I have been using.

var fileURLS = [URL]()

let fileData = getCode().data(using: String.Encoding.utf8)
var fileName = "\(self.drawing.getDrawingName()).\(self.getCodeExtension())"

fileName = fileName.components(separatedBy: CharacterSet.illegalCharacters).joined(separator: "")

let localDir = NSTemporaryDirectory()
let localPath = localDir.appendingFormat("%@", fileName)
fileURLS.append(URL(fileURLWithPath: localPath))
try? fileData?.write(to: URL(fileURLWithPath: localPath), options: .atomic)

When I open the file I am trying to replicate it says it is 77bytes with hexadecimal encoding, but when I try to create the same using Swift it comes out much larger with utf8 encoding. Now I know I am using UTF8 but I can't figure out how to retain what I have above and what encoding I can use that will write it as hexadecimal encoding.

Hopefully that makes sense.

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
Skyler Lauren
  • 3,792
  • 3
  • 18
  • 30
  • 1
    Possibly helpful: https://stackoverflow.com/a/40278391/1187415. That method requires that all whitespace is removed first, but it should not be too difficult to modify it to ignore whitespace. – Martin R Oct 29 '18 at 12:04
  • @MartinR I tried what you provided but encoding still comes up with UTF-16 LE and is 384 bytes. Really kind of stuck here. It is like I did the encoding already or something and just need to save it as raw data. – Skyler Lauren Oct 31 '18 at 01:40

1 Answers1

0

What I was originally doing was: Binary->Decimal->Hex string->Data->File

What seemed to solve my issue was to do: Binary->UInt8 Array->Data->File

Creating Data directly from [UInt8] took care of converting it to hex, spacing, and retained the hexadecimal encoding I needed.

Hopefully that helps someone else having similar issues.

Skyler Lauren
  • 3,792
  • 3
  • 18
  • 30