字符串与二进制互相转化(不包含汉字)

[入库:2005年8月18日] [更新:2007年3月24日]

本文简介:选择自 qthinker 的 blog

对于二进制与字符的互换,是由于我要做des加密程序的需要才设计的
现在把我的源程序发布:

先建立一个工程
在框架上画
两个textbox,命名为text1,text2
两个commandbutton, 命名为command1,command1
其他定义自己去该吧!

rem 此程序由qthinker制作,免费发布,可以修改,请保留此信息
option base 1
private function byte2bit(s as string) as string
dim i as integer, j as integer, k as integer, ilen as integer
dim by() as string
dim b() as integer
ilen = len(s)
redim by(ilen)
redim b(ilen / 8)
for k = 1 to ilen
 by(k) = mid$(s, k, 1)
 next k

for i = 1 to (ilen / 8)
if by(1 + 8 * (i - 1)) = "1" then
b(i) = b(i) or &h80
else
b(i) = b(i) and &h7f
 end if
if by(2 + 8 * (i - 1)) = "1" then
 b(i) = b(i) or &h40
 else
  b(i) = b(i) and &hbf
end if
 if by(3 + 8 * (i - 1)) = "1" then
 b(i) = b(i) or &h20
 else
  b(i) = b(i) and &hdf
end if
 if by(4 + 8 * (i - 1)) = "1" then
 b(i) = b(i) or &h10
 else
 b(i) = b(i) and &hef
  end if
 if by(5 + 8 * (i - 1)) = "1" then
 b(i) = b(i) or &h8
 else
 b(i) = b(i) and &hf7
 
end if
 if by(6 + 8 * (i - 1)) = "1" then
 b(i) = b(i) or &h4
 else
 b(i) = b(i) and &hfb
end if
  if by(7 + 8 * (i - 1)) = "1" then
  b(i) = b(i) or &h2
  else
 b(i) = b(i) and &hfd
 end if
if by(8 + 8 * (i - 1)) = "1" then
 b(i) = b(i) or "1"
 else
 b(i) = b(i) and &hfe
end if
byte2bit = byte2bit & chr$(b(i))

 next i
end function
private function bit2byte(s as string) as string
dim s2 as string
dim x as string
dim i as integer, k as integer
dim ilen as integer

ilen = len(s)
dim b()
dim s1()
redim s1(ilen)
redim b(ilen * 8)
s2 = ""
for i = 1 to ilen
 x = mid$(s, i, 1)
 s1(i) = asc(x)

  if s1(i) and &h80 then
     b(1 + 8 * (i - 1)) = 1
  else
     b(1 + 8 * (i - 1)) = 0
   end if

  if s1(i) and &h40 then
      b(2 + 8 * (i - 1)) = 1
   else
   b(2 + 8 * (i - 1)) = 0
   end if
 
  if s1(i) and &h20 then
     b(3 + 8 * (i - 1)) = 1
   else
   b(3 + 8 * (i - 1)) = 0
   end if

if s1(i) and &h10 then
      b(4 + 8 * (i - 1)) = 1
   else
   b(4 + 8 * (i - 1)) = 0
   end if


if s1(i) and &h8 then
     b(5 + 8 * (i - 1)) = 1
   else
   b(5 + 8 * (i - 1)) = 0
   end if
 
if s1(i) and &h4 then
     b(6 + 8 * (i - 1)) = 1
   else
   b(6 + 8 * (i - 1)) = 0
   end if
 
if s1(i) and &h2 then
    b(7 + 8 * (i - 1)) = 1
   else
   b(7 + 8 * (i - 1)) = 0
   end if
 
if s1(i) and "1" then
     b(8 + 8 * (i - 1)) = 1
else
   b(8 + 8 * (i - 1)) = 0
   end if
 
next i

for k = 1 to ilen * 8
 s2 = s2 & b(k)
  if k mod 8 = 0 then
     s2 = s2
  end if
 next k
bit2byte = s2
end function

private sub command1_click()
dim s as string
dim s2 as string
s = text1.text
s2 = bit2byte(s)
text2.text = s2
end sub

private sub command2_click()
dim s as string
dim s1 as string
s = text2.text
s1 = byte2bit(s)
text2.text = s1
end sub

本文关键:通过了运行和测试
  相关方案
Google
 

本站最佳浏览方式为 分辨率 1024x768 IE 6.0(或更高版本的 IE浏览器)

go top