New random range procedure.

General FreeBASIC programming questions.
neil
Posts: 594
Joined: Mar 17, 2022 23:26

Re: New random range procedure.

Post by neil »

What's wrong with this? Should I remove it from my opening post Cryptanalysis thread? It seems to work OK.

Code: Select all

#define CrLf Chr(10, 13)
#define enc 1
#define dec -1

' ------------------------------------------------------------
Function KnuthRange( Byval seed As UlongInt, Byref BeenHere As Boolean ) As Ubyte
#define IRange( f, l ) Int( _Rand/2^64*( (l+1) - (f) ) + (f) )
Static As Ulongint _Rand
  If BeenHere = False Then
    _Rand = seed
    BeenHere =True
  End If
  _Rand = 6364136223846793005ull * _Rand + 1442695040888963407ull
  Return IRange(0,255)
End Function

Sub EncDec( Byref message As String, Byval seed as Ulongint, Byval rounds As Ulong, ByVal flag As Long )
Dim As ULong  k = Len(message), temp
Dim As Boolean bh
  For i As Ulong = 1 to rounds
    For j As Ulong = 1 To k
      temp = KnuthRange( seed, bh )
      message[j-1] = Asc(message, j) + temp*IIf( (temp <= 128), flag, -flag ) ' Random addition/subtraction
    Next
  Next
End Sub
' ------------------------------------------------------------

' Example usage
Dim s As String
Dim As Double t

s = "The time has come the walrus said" + CrLf
s += "to talk of many things" + CrLf
s += "of shoes, and ships, and sealing wax," + CrLf
s += "of cabbages, and kings," + CrLf
s += "and why the sea is boiling hot," + CrLf
s += "and whether pigs have wings."

Print s + CrLf
t = Timer
EncDec( s, 123456789, 10, enc ) ' Note enc for encryption
t = Timer - t
Print s + CrLf
EncDec( s, 123456789, 10, dec ) ' Note dec for decryption
Print s
Print
Print Int(t*1000000);" microseconds"

Sleep
neil
Posts: 594
Joined: Mar 17, 2022 23:26

Re: New random range procedure.

Post by neil »

This could be useful.

Improving on QBasic's Random Number Generator. By Chris Wellons
https://nullprogram.com/blog/2020/11/17/
deltarho[1859]
Posts: 4313
Joined: Jan 02, 2017 0:34
Location: UK
Contact:

Re: New random range procedure.

Post by deltarho[1859] »

What's wrong with this?
Nothing as such. My latest versions simply remove the BeenHere logic, which is tested every time we enter KnuthRange.
Post Reply