」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > Go語言中如何高效地將字符串轉換為字節數組?

Go語言中如何高效地將字符串轉換為字節數組?

發佈於2025-04-13
瀏覽:277

How Can Strings Be Efficiently Converted to Byte Arrays in Go?
訪問字符串值作為bytes

訪問字節陣列允許低級數據操作和對二進制數據的操縱。實現此目的的一種方法是利用一個循環在字符串中的字節範圍內迭代,將每個字節分配給字節數組中的等效索引。

package main 進口 ( “ FMT” ) func main(){ var arr [20]字節 str:=“ ABC” //通過字節迭代並分配給字節數組 對於k,v:= range [] byte(str){ arr [k] =字節(v) } //在字節數組中顯示值 fmt.println(arr) }An alternative, more concise and secure approach is to use type conversion:

[]byte("Here is a string....")

package main

import (
    "fmt"
)

func main() {
    var arr [20]byte
    str := "abc"

    // Iterate through bytes and assign to byte array
    for k, v := range []byte(str) {
        arr[k] = byte(v)
    }

    // Display the values in the byte array
    fmt.Println(arr)
}
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3