B4J Question How to calculate this pseudo-random number without unsigned int?

kimstudio

Active Member
Licensed User
Longtime User
Dear all,

Since we don't have unsigned int how can I convert this code to B4J?
In the following code seems unsigned long is actually unsigned int as it is 32 bit. Thanks!

C:
/* Calculate pseudo-random 32 bit number based on linear congruential method. */
unsigned long GenerateRandomNumber( void )
{
   /* Change this for different random sequences. */
   static unsigned long randSeed = 22222;
   randSeed = (randSeed * 196314165) + 907633515;
   return randSeed;
}
 

Brian Dean

Well-Known Member
Licensed User
Longtime User
Maybe I am misreading your code fragment but it seems to me that the GenerateRandomNumber function is always going to return the same value, -285764591. This may be a signed int, but it is nonetheless a 32-bit value (0xEEF79411). There is no problem passing this value around in B4X.

Not knowing the context in which this value is going to be used makes it difficult to say more.

[Edit : I probably put that the wrong way round. I should have said that the code fragment produces the value 0xEEF79411 which is an acceptable int value (-285764591) in B4J.]
 
Last edited:
Upvote 0

William Lancee

Well-Known Member
Licensed User
Longtime User
B4X:
    RndSeed(22222)   'if you want the same pseudo random sequence every time
    Dim longRandom As Long = Rnd(0, 2147483647)
    'this wil give you a 64bit integer between 0 and max 'signed' 32 bit int
    'double this and randomly add 0 or 1
    longRandom = 2 * longRandom + Rnd(0, 2)
 
Upvote 0

kimstudio

Active Member
Licensed User
Longtime User
Maybe I am misreading your code fragment but it seems to me that the GenerateRandomNumber function is always going to return the same value, -285764591. This may be a signed int, but it is nonetheless a 32-bit value (0xEEF79411). There is no problem passing this value around in B4X.

Not knowing the context in which this value is going to be used makes it difficult to say more.

[Edit : I probably put that the wrong way round. I should have said that the code fragment produces the value 0xEEF79411 which is an acceptable int value (-285764591) in B4J.]

Thanks Brian. This is actually C code so it has static variable like a global variable. I did find that passing the int value to B4J I get a random number between -INT_MAX to INT_MAX, instead of 0 to UINT_MAX, but it works like a random generator just with negative values.
 
Upvote 0

kimstudio

Active Member
Licensed User
Longtime User
B4X:
    RndSeed(22222)   'if you want the same pseudo random sequence every time
    Dim longRandom As Long = Rnd(0, 2147483647)
    'this wil give you a 64bit integer between 0 and max 'signed' 32 bit int
    'double this and randomly add 0 or 1
    longRandom = 2 * longRandom + Rnd(0, 2)

This is clever to get a UINT random number!
 
Upvote 0
Top