Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix Random.Next returns negative numbers #405 #840

Merged
merged 1 commit into from
Sep 5, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/CLR/CorLib/corlib_native_System_Random.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ HRESULT Library_corlib_native_System_Random::Next___I4( CLR_RT_StackFrame& stack

NANOCLR_CHECK_HRESULT(GetRandom( stack, rand ));

stack.SetResult_I4( rand->Next() );
stack.SetResult_I4( rand->Next() & 0x7FFFFFFF );
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Isn't simply casting a less "expensive" operation as it just gets compiled without requiring any extra operations (ANDing with 0x7FFFFFFF)?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No. Casting for instance 0xFFFFFFFF which is a valid return value from rand->Next() into an int32 results in the value -1. So I think we need ANDing or modulo operation like % 0x7FFFFFFF

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK! so we have a winner! 👍

Copy link
Contributor

@doingnz doingnz Sep 5, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Personally I am inclined to avoid "magic values" in code. Maybe in the future we could use & Int32.MaxValue which is equivalent to the implemented & 0x7FFFFFFF as it helps the source code to be "self documenting" as to why the specific mask is being applied.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@doingnz I don't know if we have access to Int32.MaxValue

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree with @doingnz .
There is a constant in the CRT lib with that value...
Or maybe a comment explaining why that is being done is good enough.


NANOCLR_NOCLEANUP();
}
Expand Down