Last active
June 10, 2020 10:29
-
-
Save sunny352/dcf57b281152f4829e1c51eb0f1d1ee9 to your computer and use it in GitHub Desktop.
golang处理C#中使用BinaryWriter/BinaryReader序列化的字符串
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package Utils | |
import ( | |
"errors" | |
"io" | |
"math" | |
) | |
func WriteCSharpString(writer io.Writer, value string) error { | |
buffer := []byte(value) | |
err := Write7BitEncodedInt(writer, int32(len(buffer))) | |
if nil != err { | |
return err | |
} | |
_, err = writer.Write(buffer) | |
if nil != err { | |
return err | |
} | |
return nil | |
} | |
func Write7BitEncodedInt(writer io.Writer, value int32) error { | |
var num uint32 | |
for num = uint32(value); num >= 128; num >>= 7 { | |
_, err := writer.Write([]byte{byte(num | 128)}) | |
if nil != err { | |
return err | |
} | |
} | |
_, err := writer.Write([]byte{byte(num)}) | |
if nil != err { | |
return err | |
} | |
return nil | |
} | |
func ReadCSharpString(reader io.Reader) (string, error) { | |
length, err := Read7BitEncodedInt(reader) | |
if nil != err { | |
return "", err | |
} | |
buffer := make([]byte, length) | |
n, err := reader.Read(buffer) | |
if nil != err { | |
return "", err | |
} | |
if n != int(length) { | |
return "", errors.New("length is not correct") | |
} | |
return string(buffer), nil | |
} | |
func Read7BitEncodedInt(reader io.Reader) (int32, error) { | |
var num1 int32 | |
var num2 int32 | |
var buffer [1]byte | |
for num2 != 35 { | |
_, err := reader.Read(buffer[:]) | |
if nil != err { | |
return 0, err | |
} | |
num3 := buffer[0] | |
num1 |= (int32(num3) & int32(math.MaxInt8)) << num2 | |
num2 += 7 | |
if (int32(num3) & 128) == 0 { | |
return num1, nil | |
} | |
} | |
return 0, errors.New("Too many bytes in what should have been a 7 bit encoded Int32.") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment