0

Edit: I got this to work (see in answers below) in VS2012, but it still doesn't properly downcast in Xcode.

I am trying to downcast from an unsigned long to an int in C++, but data loss seems inevitable:

unsigned long bigInt= randomBigNumber;
int x = 2;

I then pass a big number to a function that accepts signed ints:

void myFunc(bigInt/(ULONG_MAX/x));

If randomBigNumber is a repeated random number -- such as in a for-loop -- I figure I should get a relatively evenly distributed number of ones and zeros, but I am only getting zeros.

How can I downcast this so as to get some ones?

Thanks.

btalbot
  • 167
  • 9
  • in case x is 2 `bigNumber > (ULONG_MAX/x)` – Bryan Chen Jul 11 '14 at 03:37
  • Right, Bryan. My problem was the way I was typing the code. I forgot to mention I was actually passing that number into a function that took a signed int (which is a big deal). – btalbot Jul 11 '14 at 03:42

2 Answers2

1

Re

I am only getting zeros

That’s because you’re dividing by a pretty big number. If the range of the random number generator is less than that big number, you can only get zeroes.


Re

How can I downcast this so as to get some ones?

You can do

myFunc(bigInt % 2);

There is however an impact on randomness. At least of old the least significant bits of a pseudo-random number were likely to be very much less than perfectly random, due to imperfect generators. So except for efficiency you might be better off doing e.g.

myFunc((bigInt / 8) % 2);

if you are interested in nice randomness. It all depends on the generator of course. And there are other more elaborate techniques for improving randomness.

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
0

I figured one way:

unsigned long bigInt = randomBigNumber;
unsigned long x = ULONG_MAX / 2;
myFunc(bigInt / x);

That worked for me. I was able to generate zero and ones. Note: I can only get this to work in VS2012, but not Xcode. Why?

btalbot
  • 167
  • 9