簡體   English   中英

如何處理 Golang 中的字節運算符?

[英]How to deal with byte operators in Golang?

我想創建一個包含昵稱和密碼等信息的緩沖區。 假設我創建了空緩沖區,即

00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00

到那時我想用數據填充它,比如buffer << nickname(string) << password(string) ,所以結果我得到

08 75 73 65 72 6e 61 6d 65 08 70 61 73 73 77 6f 72 64

這是len.nickname actual_nickname len.password password

現在,在我創建了這樣的緩沖區之后,我想將它解析為變量。 那看起來像buffer >> nickname(string) >> password(string)

我曾經在使用運算符的 c++ 中做了一些事情,但我不確定如何在 Golang 中這樣做。

這些緩沖區將用作我的網絡應用程序中的數據包主體。 我不想使用結構,但有點像上面。

我希望我正確解釋了我的問題。 我也不想使用像:這樣的拆分器將它們放入數組表中。

謝謝你。

嘗試使用bytes.Buffer ,您可以根據需要寫入,包括在必要時使用fmt.Fprintf 當所有內容都寫入緩沖區時,您可以將字節取出。

buf := bytes.NewBuffer(nil)
fmt.Fprint(buf, nickname)
fmt.Fprint(buf, password)
fmt.Print(buf.Bytes())

這里的工作示例: https : //play.golang.org/p/bRL6-N-3qH_n

您可以使用encoding/binary包進行固定大小的編碼,包括選擇字節序。

下面的示例以網絡字節順序存儲為uint32的長度寫入兩個字符串。 這適合通過網絡發送。 如果您確定這足以表示字符串長度,您可以使用uint16 ,甚至uint8

警告:我將忽略此示例代碼中的所有錯誤。 請不要在你的身上這樣做。

package main

import (
    "bytes"
    "encoding/binary"
    "fmt"
)

func main() {
    user := "foouser"
    password := "barpassword"

    // Write "len(user) user len(password) password".
    // Lengths are unsigned 32 bit ints in network byte order.
    var buf bytes.Buffer
    binary.Write(&buf, binary.BigEndian, (uint32)(len(user)))
    buf.WriteString(user)
    binary.Write(&buf, binary.BigEndian, (uint32)(len(password)))
    buf.WriteString(password)

    var output []byte = buf.Bytes()
    fmt.Printf("% x\n", output)

    // Now read it back (we could use the buffer,
    // but let's use Reader for clarity)
    input := bytes.NewReader(output)
    var uLen, pLen uint32

    binary.Read(input, binary.BigEndian, &uLen)
    uBytes := make([]byte, uLen)
    input.Read(uBytes)
    newUser := string(uBytes)

    binary.Read(input, binary.BigEndian, &pLen)
    pBytes := make([]byte, pLen)
    input.Read(pBytes)
    newPassword := string(pBytes)

    fmt.Printf("User: %q, Password: %q", newUser, newPassword)
}

這將輸出字節數組和從中提取的字符串:

00 00 00 07 66 6f 6f 75 73 65 72 00 00 00 0b 62 61 72 70 61 73 73 77 6f 72 64
User: "foouser", Password: "barpassword"

游樂場鏈接

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM