0

I have a .DAT file with Hebrew text, I want to decode the data. When trying to decode using text editors on Mac (BBEdit, Sublime or TextEdit) the Hebrew text becomes gibberish.

The file originally was in this format:

1081             310120     310120      197700  $ ‰˜…ˆ‰” .” .–…„ 01/20           01

And i've managed to change it to this format:

1081             310120     310120      197700  $ èâòÖàâî .î .ñÖÑ 01/20           01

When trying an online decoder: http://www.online-decoder.com/he it works and decode by default from macCroatian to IBM862, but there is no such encoding in Swift.

I found a library which I think that can help me do that, but can't add it to my project: https://www.example-code.com/swift3/load_text_file_using_code_page.asp

What is the best way to decode the .DAT file in Swift?

ytpm
  • 4,962
  • 6
  • 56
  • 113
  • “I have a .DAT file with Hebrew text, I want to encode the data” Did you mean decode? – Alexander Mar 05 '21 at 15:33
  • 1
    `'‰˜…ˆ‰” .” .–…„'.encode('cp1255').decode('cp862')` returns `'ירוטיפ .פ .צוה'`; however, I don't know whether it's meaningful Hebrew… Please add Hebrew equivalent to your [mcve]. (code given in Python) – JosefZ Mar 05 '21 at 17:58
  • @Alexander Yeah, sorry, I meant decode. – ytpm Mar 05 '21 at 23:01
  • @JosefZ Thank you. Yes, the result that you've pasted is Hebrew. But didn't quite understand how to decode it using Swift... – ytpm Mar 05 '21 at 23:03
  • 1
    I'd try [`init(contentsOfFile:encoding:)`](https://developer.apple.com/documentation/foundation/nsstring/1412610-init) Returns an NSString object initialized by reading data from the file at a given path using a given encoding. Related: [Hebrew Characters in Swift](https://stackoverflow.com/questions/32521515/hebrew-characters-in-swift). Sorry, I don't understand :Swift_… – JosefZ Mar 06 '21 at 10:55

1 Answers1

0

So after some research I came across this question which helped me put out this code from first answer:

if let filepath = Bundle.main.path(forResource: "somefile", ofType: "dat") {
    do {                
        let encoding = "cp862" // String encoding
        let converted = CFStringConvertIANACharSetNameToEncoding(encoding as CFString)
        let encoded = CFStringConvertEncodingToNSStringEncoding(converted)
        let sEncoding = String.Encoding(rawValue: se)
        let contents = try String(contentsOfFile: filepath, encoding: sEncoding)
    } catch {
        // contents could not be loaded
    }
} else {
    // example.txt not found!
}
ytpm
  • 4,962
  • 6
  • 56
  • 113