用golang实现7bit的编解码,不介绍7bit编码了,直接上代码
用到的外部包:
"github.com/axgle/mahonia"
解码代码:
func Bit2string(str string) string {
d := make([]byte, len(str)/2)
for i := 0; i < len(str); i = i + 2 {
d[i/2] = (byte)(StringToInt64(str[i : i+2]))
}
othermask := []byte{0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe}
mymask := []byte{0x7f, 0x3f, 0x1f, 0x0f, 0x07, 0x03, 0x01}
other := byte(0)
temp := byte(0)
sb := bytes.Buffer{}
for i := 0; i < len(d); i++ {
n := i % 7
var index uint = uint(n)
temp = d[i]
// 得到我的数据
d[i] = (byte)(d[i] & mymask[index])
d[i] = (byte)(d[i] << index)
if index != 0 {
d[i] = (byte)(d[i] & othermask[7-index])
other = (byte)(other >> (8 - index))
other = (byte)(other & mymask[7-index])
d[i] = (byte)(d[i] | other)
}
// 先把下一个数据信息拿走
other = (byte)(temp & othermask[index])
sb.WriteString(string(d[i]))
if index == 6 {
other = (byte)(other >> 1)
other = (byte)(other & 0x7f)
sb.WriteString(string(other))
}
}
return sb.String()
}
编码代码
func Encode7bit(src string) string {
srcbytes := []byte(src)
var buffer bytes.Buffer
left := byte(0)
j := 0
for i := 0; i < len(srcbytes); i++ {
j = i & 7
var index uint = uint(j)
if j == 0 {
left = srcbytes[i]
if i == len(srcbytes)-1 {
buffer.WriteString(fmt.Sprintf("%02x", left))
}
} else {
value := (byte)((srcbytes[i] << (8 - index)) | left)
left = (byte)(srcbytes[i] >> index)
buffer.WriteString(fmt.Sprintf("%02x", value))
if i == len(srcbytes)-1 {
buffer.WriteString(fmt.Sprintf("%02x", left))
}
}
}
return strings.ToUpper(mahonia.NewEncoder("UTF-8").ConvertString(buffer.String()))
}
例:
7bit编码内容
C43728FFAE83D6EEF71D1416BFEB7490B24C17CAC369F7DC05
解码之后内容
Do you know about JetBrains.