[英]Easiest way to covert part of a byte array to uint16
如果我是字節數組:
byte_array := []byte("klm,\x15\xf1\n")
我想以LittleEndian順序將字節\\ x15和\\ xf1添加到uint16。 這樣做最簡單的方法是什么?
嘗試以下方法:
var new_uint uint16
bff := bytes.newRead(byte_array[4:5])
err = binary.Read(buff, binary.LittleEndian, &new_uint)
但我一無所獲,這是相對復雜的,是否有更簡單的方法呢?
謝謝...
您有2個選項,使用像您已經做過的binary.LittleEndian,更短的方法是:
u16 := binary.LittleEndian.Uint16(byte_array[4:])
或者如果你喜歡生活危險,你可以使用不安全:
// This will return the wrong number on a BE system,
// also unsafe is not available on GAE.
u16 := *(*uint16)(unsafe.Pointer(&byte_array[4]))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.