mark 生成随机汉字
全局代码
Public Function CreateCode(strlength As Integer) As String
Dim str As String
'定义一个字符串数组储存汉字编码的组成元素
Dim r As String() = {"0", "1", "2", "3", "4", "5", _
"6", "7", "8", "9", "a", "b", _
"c", "d", "e", "f"}
'
'每循环一次产生一个含两个元素的十六进制字节数组,并将其放入bject数组中
' 每个汉字有四个区位码组成
' 区位码第1位和区位码第2位作为字节数组第一个元素
' 区位码第3位和区位码第4位作为字节数组第二个元素
'
For i As Integer = 0 To strlength - 1
'区位码第1位
Dim r1 As Integer = Rand.[Next](11, 14)
Dim str_r1 As String = r(r1).Trim()
'区位码第2位
'更换随机数发生器的种子避免产生重复值
Dim r2 As Integer
If r1 = 13 Then
r2 = Rand.[Next](0, 7)
Else
r2 = Rand.[Next](0, 16)
End If
Dim str_r2 As String = r(r2).Trim()
'区位码第3位
Dim r3 As Integer = Rand.[Next](10, 16)
Dim str_r3 As String = r(r3).Trim()
'区位码第4位
Dim r4 As Integer
If r3 = 10 Then
r4 = Rand.[Next](1, 16)
ElseIf r3 = 15 Then
r4 = Rand.[Next](0, 15)
Else
r4 = Rand.[Next](0, 16)
End If
Dim str_r4 As String = r(r4).Trim()
'定义两个字节变量存储产生的随机汉字区位码
Dim byte1 As Byte = Convert.ToByte(str_r1 & str_r2, 16)
Dim byte2 As Byte = Convert.ToByte(str_r3 & str_r4, 16)
'将两个字节变量存储在字节数组中
Dim str_r As Byte() = New Byte() {byte1, byte2}
Dim gb As Encoding = Encoding.GetEncoding("gb2312")
str &= gb.GetString(str_r)
Next
Return str
End Function
调用代码
msgbox(CreateCode(20))