Binary.FromText แปลงสตริงข้อความเป็นข้อมูลไบนารี่ที่สามารถใช้กับการเข้ารหัส Base64 หรือ Hex ได้
= Binary.FromText(text, encoding)
= Binary.FromText(text, encoding)
| Argument | Type | Required | Default | Description |
|---|---|---|---|---|
| text | text | Yes | สตริงข้อความที่ต้องการแปลงเป็นไบนารี่ (อาจเป็น Base64 หรือ Hex) | |
| encoding | number | Optional | BinaryEncoding.Base64 | การเข้ารหัสที่ใช้: BinaryEncoding.Base64 หรือ BinaryEncoding.Hex |
Binary.FromText("SGVsbG8gV29ybGQ=")= Binary.FromText("SGVsbG8gV29ybGQ=")
ข้อมูลไบนารี่ที่แปลงมาจาก Base64
Binary.FromText("48656C6C6F", BinaryEncoding.Hex)= Binary.FromText("48656C6C6F", BinaryEncoding.Hex)
ข้อมูลไบนารี่จากการเข้ารหัส Hex
let Source = Json.Document(Web.Contents("https://api.example.com/image")), Base64Image = Source[imageData], BinaryData = Binary.FromText(Base64Image) in BinaryD…let
Source = Json.Document(Web.Contents("https://api.example.com/image")),
Base64Image = Source[imageData],
BinaryData = Binary.FromText(Base64Image)
in
BinaryData
ข้อมูลไบนารี่ของรูปภาพที่สามารถบันทึกเป็นไฟล์
let ConvertToBinary = (input as text, encodingType as text) => let Encoding = if encodingType = "hex" then BinaryEncoding.Hex else BinaryEncoding.Base64, Result…let
ConvertToBinary = (input as text, encodingType as text) =>
let
Encoding = if encodingType = "hex" then BinaryEncoding.Hex else BinaryEncoding.Base64,
Result = Binary.FromText(input, Encoding)
in
Result
in
ConvertToBinary("1A2B3C", "hex")
ไบนารี่ที่แปลงจาก Hex
Binary.FromText แปลงจากข้อความไปเป็นไบนารี่ ส่วน Binary.ToText ทำการตรงกันข้าม คือแปลงจากไบนารี่เป็นข้อความ ผมใช้ FromText เมื่อต้องอ่านข้อมูลจาก API หรือไฟล์ที่อยู่ในรูป Base64
ฟังก์ชันนี้ต้องการให้ข้อความเป็น Base64 หรือ Hex จริงๆ ถ้าส่งข้อความธรรมชาติธรรมดา (Plain Text) จะเกิด Error ต้องใช้ Text.ToBinary แทน
ผมแนะนำให้ใช้ Base64 สำหรับการส่งข้อมูลทั่วไป เพราะ Base64 compatible กับระบบส่วนใหญ่ ส่วน Hex ใช้เมื่อทำงานกับข้อมูล byte-level หรือ protocol ที่ต้อง Hex เฉพาะเจาะจง
Binary.FromText แปลงข้อความธรรมชาติให้เป็นข้อมูลไบนารี่ โดยระบุการเข้ารหัส (encoding) ที่ต้องการใช้ เช่น Base64 หรือ Hex ถ้าไม่ระบุจะใช้ Base64 เป็นค่าเริ่มต้น
ที่เจ๋งคือสามารถรองรับการเข้ารหัสหลายแบบ ทำให้สามารถแปลงข้อความที่อยู่ในรูปแบบต่างๆ ได้ เช่น API responses ที่เป็น Base64 หรือข้อมูล Hex ที่นำมาจากแหล่งอื่น
ส่วนตัวผมใช้บ่อยเมื่อต้องดึงข้อมูลรูปภาพหรือไฟล์จาก API ที่ส่งกลับมาเป็น Base64 string แล้วต้องแปลงกลับเป็นไบนารี่เพื่อบันทึกไฟล์