我在VBA的MS 2010下工作(不是专家),我想根据一个字符串作为种子生成一个随机数(几个数字会更好)。
我知道Rnd(seed)用种子作为负数存在。但是,我不知道有一个字符串作为种子的随机生成器。也许是某种带有数字的散列函数?
我想要的是:
print function("abc")
45
print function("xyz abc-5")
86
print function("abc")
45在种子字符串中支持空格、符号和数字。
我可能会看到一个解决办法,通过将每个字符转换成对应的ascii数,并以某种方式使用这个大数字作为Rnd的种子,但它确实让人感觉很牵强。有谁知道有一种更好的方法吗?
发布于 2019-06-20 12:27:48
结合这些例子
至:
Function hash4(txt)
' copied from the example
Dim x As Long
Dim mask, i, j, nC, crc As Integer
Dim c As String
crc = &HFFFF
For nC = 1 To Len(txt)
j = Asc(Mid(txt, nC)) ' <<<<<<< new line of code - makes all the difference
' instead of j = Val("&H" + Mid(txt, nC, 2))
crc = crc Xor j
For j = 1 To 8
mask = 0
If crc / 2 <> Int(crc / 2) Then mask = &HA001
crc = Int(crc / 2) And &H7FFF: crc = crc Xor mask
Next j
Next nC
c = Hex$(crc)
' <<<<< new section: make sure returned string is always 4 characters long >>>>>
' pad to always have length 4:
While Len(c) < 4
c = "0" & c
Wend
Dim Hex2Dbl As Double
Hex2Dbl = CDbl("&h0" & c) ' Overflow Error if more than 2 ^ 64
If Hex2Dbl < 0 Then Hex2Dbl = Hex2Dbl + 4294967296# ' 16 ^ 8 = 4294967296
hash4 = Hex2Dbl
End Function立即尝试( VBA编辑器窗口中的Ctrl+ G ):
?hash4("Value 1")
31335
?hash4("Value 2")
31527 这一职能将:
https://stackoverflow.com/questions/56682273
复制相似问题