Random 64 not working as expected

Hi,

I’m not sure if I’m doing something wrong but I tried the following examples:

int64 RandNum = UKismetMathLibrary::RandomInteger64(MAX_int64);
	UE_LOG(LogTemp, Warning, TEXT("Num: %lld"), RandNum);

The result of this is always -2147483648

I also tried a unit32 as the max value:

int64 RandNum = UKismetMathLibrary::RandomInteger64(MAX_uint32);
	UE_LOG(LogTemp, Warning, TEXT("Num: %lld"), RandNum);

This gave some valid values but often giving the -2147483648

After some digging I suspect the issue is if we look at the implementation of RandHelpr64 which is ultimately the function called to get the result

UE_NODISCARD static FORCEINLINE int64 RandHelper64(int64 A)
	{
		return A > 0 ? Min<int64>(TruncToInt(FRand() * (float)A), A - 1) : 0;
	}

I made a similar implementation but changed TruncToInt with TruncToInt64 and I was able to get big random values as you would expect using int64.

This is what I tested with

int64 RandNum = FMath::TruncToInt64(FMath::FRand() * (float)MAX_int64);
	UE_LOG(LogTemp, Warning, TEXT("Num: %lld"), RandNum);

The result

LogTemp: Warning: Num: 4998303443811565568
LogTemp: Warning: Num: 1939421825725366272
LogTemp: Warning: Num: 745087009499906048
LogTemp: Warning: Num: 2432299490791653376
LogTemp: Warning: Num: 5232779246237122560
LogTemp: Warning: Num: 8226075957799157760
LogTemp: Warning: Num: 3087874777637978112
LogTemp: Warning: Num: 8198208835593175040
LogTemp: Warning: Num: 6282994819937599488
LogTemp: Warning: Num: 1214601633023918080
LogTemp: Warning: Num: 2072282000462446592
LogTemp: Warning: Num: 3047059531625398272
LogTemp: Warning: Num: 1886502880836321280
LogTemp: Warning: Num: 4361024855085154304
LogTemp: Warning: Num: 944095865348292608
LogTemp: Warning: Num: 828687620203610112

Is that actually the issue or what’s happening here ? Thank you.

IIRC, it’s actually the issue with converting to string.
I was trying to store player SteamID in an int64 variable instead of strings, since it generally consists of 17 digits and int32 just can’t hold that many; but I believe converting int64 to string first makes int32 out of it, and then converts the result to string, therefore I was getting negative values similar to your case.

In my case it’s not because the last example produced valid values, I can for example log the max int64 number and it would log correctly.
UE_LOG(LogTemp, Warning, TEXT("Num: %lld"), MAX_int64);
I’m logging to the console and I’m using %lld which takes and logs int64 just fine.

I only get one negative value which seems to be the max value of int32, TruncToInt is supposed to return an int32 which explains the issue.