用goalng实现7bit编解码

用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.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值