Skip to content

Instantly share code, notes, and snippets.

@benigumocom
Last active June 10, 2024 16:55
Show Gist options
  • Save benigumocom/763ecadf7d177d08c5ac3178f9581cf1 to your computer and use it in GitHub Desktop.
Save benigumocom/763ecadf7d177d08c5ac3178f9581cf1 to your computer and use it in GitHub Desktop.
【Swift】 文字コードの変換 を整理してみた 👉 https://android.benigumo.com/20240611/encoding/
// with:
// FileManageExtensions.swift
// https://gist.github.com/benigumocom/6a8e4506438b5260469c12b1c12c0fb7
do {
let documents = URL.documentsDirectory
let text = "あいうえお"
// convert to data bytes
print(
text.data(using: .shiftJIS)!,
text.data(using: .shiftJIS)!.map { String(format: "%02X", $0) }.joined()
)
print(
text.data(using: .utf8)!,
text.data(using: .utf8)!.map { String(format: "%02X", $0) }.joined()
)
// 10 bytes 82A082A282A482A682A8
// 15 bytes E38182E38184E38186E38188E3818A
print()
fileManager.showContents()
print()
// /HOME/Documents/
// create source file
let source = documents.appending(component: "sourceS.txt")
try! text.write(to: source, atomically: true, encoding: .shiftJIS)
fileManager.showContents()
print()
// /HOME/Documents/
// /HOME/Documents/sourceS.txt [10 bytes]
// file to Data
let data = try! Data(contentsOf: source)
print(data) // 10 bytes ← Shift_JIS
print()
// remove source file
try! fileManager.removeItem(at: source)
fileManager.showContents()
print()
// /HOME/Documents/
// Data to String
let string = String(data: data, encoding: .shiftJIS)! // convert
print(string) // あいうえお
print()
// String to Data
let dataS = string.data(using: .shiftJIS)! // convert
print(dataS) // 10 bytes
print()
let dataU = string.data(using: .utf8)!
print(dataU) // 15 bytes
print()
// Data to file
let fileS = documents.appending(component: "textS.txt")
let fileU = documents.appending(component: "textU.txt")
try! dataS.write(to: fileS)
try! dataU.write(to: fileU)
fileManager.showContents()
print()
// /HOME/Documents/
// /HOME/Documents/textU.txt [15 bytes]
// /HOME/Documents/textS.txt [10 bytes]
// file to String
let stringS = try String(contentsOf: fileS, encoding: .shiftJIS) // convert
let stringU = try String(contentsOf: fileU, encoding: .utf8)
print(stringS, stringU) // あいうえお あいうえお
print(stringS == stringU)
print()
// remove result files
try fileManager.removeItem(at: fileS)
try fileManager.removeItem(at: fileU)
fileManager.showContents()
print()
// /HOME/Documents/
// String to file
try stringS.write(to: fileS, atomically: true, encoding: .shiftJIS) // convert
try stringU.write(to: fileU, atomically: true, encoding: .utf8)
fileManager.showContents()
print()
// /HOME/Documents/
// /HOME/Documents/textU.txt [15 bytes]
// /HOME/Documents/textS.txt [10 bytes]
// remove result files
try fileManager.removeItem(at: fileS)
try fileManager.removeItem(at: fileU)
fileManager.showContents()
print()
// /HOME/Documents/
} catch {
print(error.localizedDescription)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment