C语言7bit编码实现,VB.Net实现7Bit编码与解码

7Bit编码主要用于对单字节字符进行编码,因为单字节字符的ASCII码在00~7F之间,最高位始终为0实际有效的只有7个Bit,因此可以通过编码的方式将无效的最高位利用起来从而达到使用7个字节存储8个单字节字符的目的。

7Bit编码的基本规则简单来说就是去掉最高位的0以后,将后一字节的低位挪到前一字节最高有效位的前面使前一字节凑够8bit,最后一个字节bit数不够8时从高位开始补0

举例说明,如果对“abc”进行7Bit编码,abc的ASCII码为0x61、0x62、0x63,其bit顺序如下:

bit7

bit6

bit5

bit4

bit3

bit2

bit1

bit0

a

0

1

1

0

0

0

0

1

b

0

1

1

0

0

0

1

0

c

0

1

1

0

0

0

1

1

编码步骤如下:

1、 将b的bit0移入a的bit7,再将b右移一位,得到如下结果

bit7

bit6

bit5

bit4

bit3

bit2

bit1

bit0

a

0

1

1

0

0

0

0

1

b

0

1

1

0

0

0

1

c

0

1

1

0

0

0

1

1

2、 将c的bit1移入b的bit7,c的bit0移入b的bit6,再将c右移两位,得到如下结果

bit7

bit6

bit5

bit4

bit3

bit2

bit1

bit0

a

0

1

1

0

0

0

0

1

b

1

1

1

1

0

0

0

1

c

0

1

1

0

0

0

3、 c剩余6bit不足8bit,在bit7、bit6补0,得到如下结果

bit7

bit6

bit5

bit4

bit3

bit2

bit1

bit0

a

0

1

1

0

0

0

0

1

b

1

1

1

1

0

0

0

1

c

0

0

0

1

1

0

0

0

abc原ASCII码为61 62 63 ,对应的7bit编码为:61 F1 18

VB.Net实现7Bit编解码的函数如下:

'7Bit编码

Private Function Encoder_7Bit(ByVal s As String) As Byte()

Dim arrAsc() As Byte

arrAsc = System.Text.Encoding.ASCII.GetBytes(s)

Dim arr7Bit() As Byte

'申请存储7Bit编码需要空间

If (arrAsc.Length * 7) Mod 8 = 0 Then

ReDim arr7Bit((arrAsc.Length * 7) \ 8 - 1)

Else

ReDim arr7Bit((arrAsc.Length * 7) \ 8)

End If

Dim lBit As Integer '低位

Dim hBit As Integer '高位

Dim yy As Integer = 0

Dim zz As Integer = 0

For xx As Integer = 1 To arrAsc.Length - 1

yy = xx Mod 8

If yy <> 0 Then

lBit = arrAsc(xx) Mod System.Math.Pow(2, yy)

hBit = arrAsc(xx) \ System.Math.Pow(2, yy)

arrAsc(xx) = hBit

arr7Bit(zz) = lBit * System.Math.Pow(2, 8 - yy) + arrAsc(xx - 1)

zz = zz + 1

End If

Next

If zz <> arr7Bit.Length Then

arr7Bit(arr7Bit.Length - 1) = arrAsc(arrAsc.Length - 1)

End If

Encoder_7Bit = arr7Bit

Erase arrAsc

Erase arr7Bit

End Function

'7Bit解码

Private Function Decoder_7Bit(ByVal s As Byte()) As String

Dim arrAsc() As Byte

'申请解码后存储ASCII字符需要的空间

ReDim arrAsc((s.Length * 8) \ 7 - 1)

Dim lBit As Integer '低位

Dim hBit As Integer '高位

Dim yy As Integer = 0

Dim zz As Integer = 0

For xx As Integer = 0 To arrAsc.Length - 1

yy = xx Mod 8

If yy <> 7 Then

lBit = s(zz) Mod System.Math.Pow(2, 8 - yy - 1)

arrAsc(xx) = lBit * System.Math.Pow(2, yy) + hBit

hBit = s(zz) \ System.Math.Pow(2, 8 - yy - 1)

zz = zz + 1

Else

arrAsc(xx) = hBit

hBit = 0

End If

Next

Decoder_7Bit = System.Text.Encoding.ASCII.GetString(arrAsc)

Erase arrAsc

End Function

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值