Home › Forums › TrueRNG Hardware random number generator › C# code example with ranging
This topic contains 0 replies, has 1 voice, and was last updated by techn0 2 years, 5 months ago.
-
AuthorPosts
-
October 21, 2020 at 10:24 am #2317
This code example returns a 32 bit random number in HEX
you can give it a min HEX and max HEX range from command line (00000000 FFFFFFFF)This should save many of you a lot of time getting going since there are not many code examples available.
I call this from a PHP script for integration into a web application.
——————————————————-
using System;
using System.IO.Ports;namespace TrueRNGRanger
{
class Program
{
static void Main(string[] args)
{
uint StartRangeInt = 0;
uint EndRangeInt = 4294967295;
string StartRange = “”;
string EndRange = “”;
if (args.Length == 2) //two command line args or bust
{
StartRange = args[0];
EndRange = args[1];
StartRangeInt = Convert.ToUInt32(StartRange, 16); //Convert HEX args to 32 bit int
EndRangeInt = Convert.ToUInt32(EndRange, 16); //Convert HEX args to 32 bit int
}
SerialPort port = new SerialPort(“COM4″);
port.DtrEnable = true;
Boolean good = false;
uint trycount = 0;
while (good == false){try{
port.Open();
good = true;
}catch{trycount++;}
} //This prevents a crash if this code is ran simultaniously in another instanceuint RandomNumber = 0; // unsigned random variable 32 bit
byte one = (byte)port.ReadByte();
byte two = (byte)port.ReadByte();
byte thr = (byte)port.ReadByte();
byte fou = (byte)port.ReadByte();
//Shift the random bytes into the 32 bit variable
RandomNumber += one;
RandomNumber = RandomNumber << 8;
RandomNumber += two;
RandomNumber = RandomNumber << 8;
RandomNumber += thr;
RandomNumber = RandomNumber << 8;
RandomNumber += fou;
//Math to put the output into the range specified
double RangeDivisor = 4294967295 / (Convert.ToDouble(EndRangeInt – StartRangeInt));
uint RangedRandomNumber = Convert.ToUInt32((RandomNumber / RangeDivisor) + StartRangeInt);
Console.WriteLine(RangedRandomNumber.ToString(“X”)); // Print Random Ranged number in HEX
port.Close();
}
}
} -
AuthorPosts
You must be logged in to reply to this topic.