Skip to content

Commit

Permalink
Fix Random() for big-endian systems
Browse files Browse the repository at this point in the history
This might be not strictly needed, but fixes failures in tests/irandom
  • Loading branch information
th-otto authored and giulianobelinassi committed May 28, 2024
1 parent 4b455e5 commit c2d93fe
Showing 1 changed file with 14 additions and 0 deletions.
14 changes: 14 additions & 0 deletions common/irandom.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
#include <stdlib.h>
#include <time.h>
#include "irandom.h"
#include "endianness.h"

unsigned int RandNumb = 0x12349876;

Expand Down Expand Up @@ -59,6 +60,18 @@ unsigned char Random()
** This treats the number as bytes so setting it on bit endian machines needs to byte swap.
*/
unsigned char* bytes = reinterpret_cast<unsigned char*>(&RandNumb);
#ifdef __BIG_ENDIAN__
unsigned char cf1 = (bytes[3] >> 1) & 1;
unsigned char tmp_a = bytes[3] >> 2;
unsigned char cf2 = (bytes[1] >> 7) & 1;
bytes[1] = (bytes[1] << 1) | cf1;
cf1 = (bytes[2] >> 7) & 1;
bytes[2] = (bytes[2] << 1) | cf2;
cf2 = (tmp_a - (RandNumb + (cf1 != 1))) & 1;
bytes[3] = (bytes[3] >> 1) | (cf2 << 7);

return bytes[2] ^ bytes[3];
#else
unsigned char cf1 = (bytes[0] >> 1) & 1;
unsigned char tmp_a = bytes[0] >> 2;
unsigned char cf2 = (bytes[2] >> 7) & 1;
Expand All @@ -69,6 +82,7 @@ unsigned char Random()
bytes[0] = (bytes[0] >> 1) | (cf2 << 7);

return bytes[1] ^ bytes[0];
#endif
}

int Get_Random_Mask(int maxval)
Expand Down

0 comments on commit c2d93fe

Please sign in to comment.