Java MOD operator returns negative value
up vote
0
down vote
favorite
I have this method:
private static int generateNo(int randomNo, int value)
return ((randomNo*value)%256);
in my example
randomNo = 17719
qValue = 197920
When I calculate it with calculator the returned value should be 224, however, when I run the program it returns -32.
can anyone explain it please.
java negative-number mod
add a comment |
up vote
0
down vote
favorite
I have this method:
private static int generateNo(int randomNo, int value)
return ((randomNo*value)%256);
in my example
randomNo = 17719
qValue = 197920
When I calculate it with calculator the returned value should be 224, however, when I run the program it returns -32.
can anyone explain it please.
java negative-number mod
2
The multiplication has overflowed integer's range.
– Andy Turner
Nov 11 at 21:07
2
And the modulus operator works like division, so it'll give a negative answer if one argument is negative.
– Yona Appletree
Nov 11 at 21:08
add a comment |
up vote
0
down vote
favorite
up vote
0
down vote
favorite
I have this method:
private static int generateNo(int randomNo, int value)
return ((randomNo*value)%256);
in my example
randomNo = 17719
qValue = 197920
When I calculate it with calculator the returned value should be 224, however, when I run the program it returns -32.
can anyone explain it please.
java negative-number mod
I have this method:
private static int generateNo(int randomNo, int value)
return ((randomNo*value)%256);
in my example
randomNo = 17719
qValue = 197920
When I calculate it with calculator the returned value should be 224, however, when I run the program it returns -32.
can anyone explain it please.
java negative-number mod
java negative-number mod
asked Nov 11 at 21:03
Java Crawler
1591314
1591314
2
The multiplication has overflowed integer's range.
– Andy Turner
Nov 11 at 21:07
2
And the modulus operator works like division, so it'll give a negative answer if one argument is negative.
– Yona Appletree
Nov 11 at 21:08
add a comment |
2
The multiplication has overflowed integer's range.
– Andy Turner
Nov 11 at 21:07
2
And the modulus operator works like division, so it'll give a negative answer if one argument is negative.
– Yona Appletree
Nov 11 at 21:08
2
2
The multiplication has overflowed integer's range.
– Andy Turner
Nov 11 at 21:07
The multiplication has overflowed integer's range.
– Andy Turner
Nov 11 at 21:07
2
2
And the modulus operator works like division, so it'll give a negative answer if one argument is negative.
– Yona Appletree
Nov 11 at 21:08
And the modulus operator works like division, so it'll give a negative answer if one argument is negative.
– Yona Appletree
Nov 11 at 21:08
add a comment |
4 Answers
4
active
oldest
votes
up vote
2
down vote
accepted
A little hint. If you have unexpected negative value when multiply (or sum) numbers, mostly this is number overflow:
private static int generateNo(int randomNo, int value)
return (int)(((long)randomNo * value) % 256);
2
This works, but I think it would be useful to explain to OP why it works.
– Yona Appletree
Nov 11 at 21:12
add a comment |
up vote
2
down vote
Java is in the camp of using a signed remainder instead of the operation that is usually meant modulus (the non-negative remainder of Euclidean division). Fortunately for powers of two there is a really easy fix: use bitwise &
. That's easier to think about anyway, since it's a trivial operation on bits, instead of the result of a complicated division algorithm.
For example:
private static int generateNo(int randomNo, int value)
return randomNo * value & 255;
This cannot possibly have a negative result since & 255
guarantees that only the low 8 bits of the result can be set, so the result is for sure in the range [0..255].
Letting the multiplication wrap first is OK if you want some of the lower bits of the result, as here (the lowest 8). It does not work properly if you want to compute (x * y) MOD p
where p
is not a power of two, because then (after working around Java's signed remainder thing) the actual computation becomes (due to wrapping) ((x * y) MOD 2³²) MOD p
. IFF p
divides 2³² (ie iff p
is a power of two not exceeding 2³²) then that simplifies down to just (x * y) MOD p
.
Or with a more bit-level view: the bits of the product are the lowest 32 bits of the "full" product (the full product of two 32 bit integers has 64 bits), of course if we only need those bits (or some subset of them, such as the lowest 8) then that's fine. But if the result we want would depend on the 32 high bits of the product, then obviously we would need to compute those bits. (x * y) MOD p
where p
is not a power of two would depend on all bits of the full product.
add a comment |
up vote
1
down vote
17719*197920 = 3506944480
, which is larger than Integer.MAX_VALUE
.
As such, the multiplication overflows the range of int, and the result is -788022816
.
Hence, taking the modulus results in a negative result.
add a comment |
up vote
1
down vote
There are two things at play here.
- Multiplying two
int
s together can result in a number larger thanInteger.MAX_VALUE
(2147483647), which wraps around to being a negative number. - Applying the modulus operator on a positive and a negative number results in a negative number.
You need to think about how you want this function to work given edge case values, like very large integers or negative numbers.
What should generateNo(-100, 50)
produce, for example?
You may want to ensure your values are positive before doing the modulus, like this:
Math.abs(randomNo * value) % 256
However, this actually has a really interesting edge case where Math.abs(Integer.MIN_VALUE) == Integer.MIN_VALUE
because it overflows.
Instead, use Math.abs
on the result:
Math.abs((randomNo * value) % 256)
I'll also offer some general critique about this function. The names don't really explain what it does. Why generateNo
? No doubt there are many ways to generate an number. I would suggest a more specific name.
The arguments, randomNo
and value
are also problematic. Why does generateNo
care if the first argument is random or not?
Specifying what you want to happen more clearly, and having names that describe those things, may make it easier to think about.
I also suggest, when having issues like this, to break down the steps so you understand what is going on. Something like:
private static int generateNo(int randomNo, int value)
final int product = randomNo * value;
final int result = product % 256;
// Breakpoint or System.out.println here, to understand the values...
return result;
2
NoteMath.abs
can produce a negative result in an unusual case. Also, typically, the result after an integer overflow will be nonsense. In this special case you can use(randomNo*value) & 0xff
.
– Tom Hawtin - tackline
Nov 11 at 21:31
Hah, you're referring to the edge case whereMath.abs(Integer.MIN_VALUE) == Integer.MIN_VALUE
? Never occurred to me, but that's actually pretty funny, and would be an amazing (and totally possible) bug in this case. I'll edit the answer to suggest usingMath.abs
on the result. That's great.
– Yona Appletree
Nov 11 at 21:59
The fact is though, the OP should really just being thinking more about what this function is supposed to do, and probably some research into integer overflow and the modulus operator.
– Yona Appletree
Nov 11 at 22:01
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53253208%2fjava-mod-operator-returns-negative-value%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
4 Answers
4
active
oldest
votes
4 Answers
4
active
oldest
votes
active
oldest
votes
active
oldest
votes
up vote
2
down vote
accepted
A little hint. If you have unexpected negative value when multiply (or sum) numbers, mostly this is number overflow:
private static int generateNo(int randomNo, int value)
return (int)(((long)randomNo * value) % 256);
2
This works, but I think it would be useful to explain to OP why it works.
– Yona Appletree
Nov 11 at 21:12
add a comment |
up vote
2
down vote
accepted
A little hint. If you have unexpected negative value when multiply (or sum) numbers, mostly this is number overflow:
private static int generateNo(int randomNo, int value)
return (int)(((long)randomNo * value) % 256);
2
This works, but I think it would be useful to explain to OP why it works.
– Yona Appletree
Nov 11 at 21:12
add a comment |
up vote
2
down vote
accepted
up vote
2
down vote
accepted
A little hint. If you have unexpected negative value when multiply (or sum) numbers, mostly this is number overflow:
private static int generateNo(int randomNo, int value)
return (int)(((long)randomNo * value) % 256);
A little hint. If you have unexpected negative value when multiply (or sum) numbers, mostly this is number overflow:
private static int generateNo(int randomNo, int value)
return (int)(((long)randomNo * value) % 256);
edited Nov 11 at 21:34
answered Nov 11 at 21:12
oleg.cherednik
5,10821016
5,10821016
2
This works, but I think it would be useful to explain to OP why it works.
– Yona Appletree
Nov 11 at 21:12
add a comment |
2
This works, but I think it would be useful to explain to OP why it works.
– Yona Appletree
Nov 11 at 21:12
2
2
This works, but I think it would be useful to explain to OP why it works.
– Yona Appletree
Nov 11 at 21:12
This works, but I think it would be useful to explain to OP why it works.
– Yona Appletree
Nov 11 at 21:12
add a comment |
up vote
2
down vote
Java is in the camp of using a signed remainder instead of the operation that is usually meant modulus (the non-negative remainder of Euclidean division). Fortunately for powers of two there is a really easy fix: use bitwise &
. That's easier to think about anyway, since it's a trivial operation on bits, instead of the result of a complicated division algorithm.
For example:
private static int generateNo(int randomNo, int value)
return randomNo * value & 255;
This cannot possibly have a negative result since & 255
guarantees that only the low 8 bits of the result can be set, so the result is for sure in the range [0..255].
Letting the multiplication wrap first is OK if you want some of the lower bits of the result, as here (the lowest 8). It does not work properly if you want to compute (x * y) MOD p
where p
is not a power of two, because then (after working around Java's signed remainder thing) the actual computation becomes (due to wrapping) ((x * y) MOD 2³²) MOD p
. IFF p
divides 2³² (ie iff p
is a power of two not exceeding 2³²) then that simplifies down to just (x * y) MOD p
.
Or with a more bit-level view: the bits of the product are the lowest 32 bits of the "full" product (the full product of two 32 bit integers has 64 bits), of course if we only need those bits (or some subset of them, such as the lowest 8) then that's fine. But if the result we want would depend on the 32 high bits of the product, then obviously we would need to compute those bits. (x * y) MOD p
where p
is not a power of two would depend on all bits of the full product.
add a comment |
up vote
2
down vote
Java is in the camp of using a signed remainder instead of the operation that is usually meant modulus (the non-negative remainder of Euclidean division). Fortunately for powers of two there is a really easy fix: use bitwise &
. That's easier to think about anyway, since it's a trivial operation on bits, instead of the result of a complicated division algorithm.
For example:
private static int generateNo(int randomNo, int value)
return randomNo * value & 255;
This cannot possibly have a negative result since & 255
guarantees that only the low 8 bits of the result can be set, so the result is for sure in the range [0..255].
Letting the multiplication wrap first is OK if you want some of the lower bits of the result, as here (the lowest 8). It does not work properly if you want to compute (x * y) MOD p
where p
is not a power of two, because then (after working around Java's signed remainder thing) the actual computation becomes (due to wrapping) ((x * y) MOD 2³²) MOD p
. IFF p
divides 2³² (ie iff p
is a power of two not exceeding 2³²) then that simplifies down to just (x * y) MOD p
.
Or with a more bit-level view: the bits of the product are the lowest 32 bits of the "full" product (the full product of two 32 bit integers has 64 bits), of course if we only need those bits (or some subset of them, such as the lowest 8) then that's fine. But if the result we want would depend on the 32 high bits of the product, then obviously we would need to compute those bits. (x * y) MOD p
where p
is not a power of two would depend on all bits of the full product.
add a comment |
up vote
2
down vote
up vote
2
down vote
Java is in the camp of using a signed remainder instead of the operation that is usually meant modulus (the non-negative remainder of Euclidean division). Fortunately for powers of two there is a really easy fix: use bitwise &
. That's easier to think about anyway, since it's a trivial operation on bits, instead of the result of a complicated division algorithm.
For example:
private static int generateNo(int randomNo, int value)
return randomNo * value & 255;
This cannot possibly have a negative result since & 255
guarantees that only the low 8 bits of the result can be set, so the result is for sure in the range [0..255].
Letting the multiplication wrap first is OK if you want some of the lower bits of the result, as here (the lowest 8). It does not work properly if you want to compute (x * y) MOD p
where p
is not a power of two, because then (after working around Java's signed remainder thing) the actual computation becomes (due to wrapping) ((x * y) MOD 2³²) MOD p
. IFF p
divides 2³² (ie iff p
is a power of two not exceeding 2³²) then that simplifies down to just (x * y) MOD p
.
Or with a more bit-level view: the bits of the product are the lowest 32 bits of the "full" product (the full product of two 32 bit integers has 64 bits), of course if we only need those bits (or some subset of them, such as the lowest 8) then that's fine. But if the result we want would depend on the 32 high bits of the product, then obviously we would need to compute those bits. (x * y) MOD p
where p
is not a power of two would depend on all bits of the full product.
Java is in the camp of using a signed remainder instead of the operation that is usually meant modulus (the non-negative remainder of Euclidean division). Fortunately for powers of two there is a really easy fix: use bitwise &
. That's easier to think about anyway, since it's a trivial operation on bits, instead of the result of a complicated division algorithm.
For example:
private static int generateNo(int randomNo, int value)
return randomNo * value & 255;
This cannot possibly have a negative result since & 255
guarantees that only the low 8 bits of the result can be set, so the result is for sure in the range [0..255].
Letting the multiplication wrap first is OK if you want some of the lower bits of the result, as here (the lowest 8). It does not work properly if you want to compute (x * y) MOD p
where p
is not a power of two, because then (after working around Java's signed remainder thing) the actual computation becomes (due to wrapping) ((x * y) MOD 2³²) MOD p
. IFF p
divides 2³² (ie iff p
is a power of two not exceeding 2³²) then that simplifies down to just (x * y) MOD p
.
Or with a more bit-level view: the bits of the product are the lowest 32 bits of the "full" product (the full product of two 32 bit integers has 64 bits), of course if we only need those bits (or some subset of them, such as the lowest 8) then that's fine. But if the result we want would depend on the 32 high bits of the product, then obviously we would need to compute those bits. (x * y) MOD p
where p
is not a power of two would depend on all bits of the full product.
edited Nov 11 at 22:58
answered Nov 11 at 21:29
harold
41.1k356108
41.1k356108
add a comment |
add a comment |
up vote
1
down vote
17719*197920 = 3506944480
, which is larger than Integer.MAX_VALUE
.
As such, the multiplication overflows the range of int, and the result is -788022816
.
Hence, taking the modulus results in a negative result.
add a comment |
up vote
1
down vote
17719*197920 = 3506944480
, which is larger than Integer.MAX_VALUE
.
As such, the multiplication overflows the range of int, and the result is -788022816
.
Hence, taking the modulus results in a negative result.
add a comment |
up vote
1
down vote
up vote
1
down vote
17719*197920 = 3506944480
, which is larger than Integer.MAX_VALUE
.
As such, the multiplication overflows the range of int, and the result is -788022816
.
Hence, taking the modulus results in a negative result.
17719*197920 = 3506944480
, which is larger than Integer.MAX_VALUE
.
As such, the multiplication overflows the range of int, and the result is -788022816
.
Hence, taking the modulus results in a negative result.
answered Nov 11 at 21:09
Andy Turner
79.4k878132
79.4k878132
add a comment |
add a comment |
up vote
1
down vote
There are two things at play here.
- Multiplying two
int
s together can result in a number larger thanInteger.MAX_VALUE
(2147483647), which wraps around to being a negative number. - Applying the modulus operator on a positive and a negative number results in a negative number.
You need to think about how you want this function to work given edge case values, like very large integers or negative numbers.
What should generateNo(-100, 50)
produce, for example?
You may want to ensure your values are positive before doing the modulus, like this:
Math.abs(randomNo * value) % 256
However, this actually has a really interesting edge case where Math.abs(Integer.MIN_VALUE) == Integer.MIN_VALUE
because it overflows.
Instead, use Math.abs
on the result:
Math.abs((randomNo * value) % 256)
I'll also offer some general critique about this function. The names don't really explain what it does. Why generateNo
? No doubt there are many ways to generate an number. I would suggest a more specific name.
The arguments, randomNo
and value
are also problematic. Why does generateNo
care if the first argument is random or not?
Specifying what you want to happen more clearly, and having names that describe those things, may make it easier to think about.
I also suggest, when having issues like this, to break down the steps so you understand what is going on. Something like:
private static int generateNo(int randomNo, int value)
final int product = randomNo * value;
final int result = product % 256;
// Breakpoint or System.out.println here, to understand the values...
return result;
2
NoteMath.abs
can produce a negative result in an unusual case. Also, typically, the result after an integer overflow will be nonsense. In this special case you can use(randomNo*value) & 0xff
.
– Tom Hawtin - tackline
Nov 11 at 21:31
Hah, you're referring to the edge case whereMath.abs(Integer.MIN_VALUE) == Integer.MIN_VALUE
? Never occurred to me, but that's actually pretty funny, and would be an amazing (and totally possible) bug in this case. I'll edit the answer to suggest usingMath.abs
on the result. That's great.
– Yona Appletree
Nov 11 at 21:59
The fact is though, the OP should really just being thinking more about what this function is supposed to do, and probably some research into integer overflow and the modulus operator.
– Yona Appletree
Nov 11 at 22:01
add a comment |
up vote
1
down vote
There are two things at play here.
- Multiplying two
int
s together can result in a number larger thanInteger.MAX_VALUE
(2147483647), which wraps around to being a negative number. - Applying the modulus operator on a positive and a negative number results in a negative number.
You need to think about how you want this function to work given edge case values, like very large integers or negative numbers.
What should generateNo(-100, 50)
produce, for example?
You may want to ensure your values are positive before doing the modulus, like this:
Math.abs(randomNo * value) % 256
However, this actually has a really interesting edge case where Math.abs(Integer.MIN_VALUE) == Integer.MIN_VALUE
because it overflows.
Instead, use Math.abs
on the result:
Math.abs((randomNo * value) % 256)
I'll also offer some general critique about this function. The names don't really explain what it does. Why generateNo
? No doubt there are many ways to generate an number. I would suggest a more specific name.
The arguments, randomNo
and value
are also problematic. Why does generateNo
care if the first argument is random or not?
Specifying what you want to happen more clearly, and having names that describe those things, may make it easier to think about.
I also suggest, when having issues like this, to break down the steps so you understand what is going on. Something like:
private static int generateNo(int randomNo, int value)
final int product = randomNo * value;
final int result = product % 256;
// Breakpoint or System.out.println here, to understand the values...
return result;
2
NoteMath.abs
can produce a negative result in an unusual case. Also, typically, the result after an integer overflow will be nonsense. In this special case you can use(randomNo*value) & 0xff
.
– Tom Hawtin - tackline
Nov 11 at 21:31
Hah, you're referring to the edge case whereMath.abs(Integer.MIN_VALUE) == Integer.MIN_VALUE
? Never occurred to me, but that's actually pretty funny, and would be an amazing (and totally possible) bug in this case. I'll edit the answer to suggest usingMath.abs
on the result. That's great.
– Yona Appletree
Nov 11 at 21:59
The fact is though, the OP should really just being thinking more about what this function is supposed to do, and probably some research into integer overflow and the modulus operator.
– Yona Appletree
Nov 11 at 22:01
add a comment |
up vote
1
down vote
up vote
1
down vote
There are two things at play here.
- Multiplying two
int
s together can result in a number larger thanInteger.MAX_VALUE
(2147483647), which wraps around to being a negative number. - Applying the modulus operator on a positive and a negative number results in a negative number.
You need to think about how you want this function to work given edge case values, like very large integers or negative numbers.
What should generateNo(-100, 50)
produce, for example?
You may want to ensure your values are positive before doing the modulus, like this:
Math.abs(randomNo * value) % 256
However, this actually has a really interesting edge case where Math.abs(Integer.MIN_VALUE) == Integer.MIN_VALUE
because it overflows.
Instead, use Math.abs
on the result:
Math.abs((randomNo * value) % 256)
I'll also offer some general critique about this function. The names don't really explain what it does. Why generateNo
? No doubt there are many ways to generate an number. I would suggest a more specific name.
The arguments, randomNo
and value
are also problematic. Why does generateNo
care if the first argument is random or not?
Specifying what you want to happen more clearly, and having names that describe those things, may make it easier to think about.
I also suggest, when having issues like this, to break down the steps so you understand what is going on. Something like:
private static int generateNo(int randomNo, int value)
final int product = randomNo * value;
final int result = product % 256;
// Breakpoint or System.out.println here, to understand the values...
return result;
There are two things at play here.
- Multiplying two
int
s together can result in a number larger thanInteger.MAX_VALUE
(2147483647), which wraps around to being a negative number. - Applying the modulus operator on a positive and a negative number results in a negative number.
You need to think about how you want this function to work given edge case values, like very large integers or negative numbers.
What should generateNo(-100, 50)
produce, for example?
You may want to ensure your values are positive before doing the modulus, like this:
Math.abs(randomNo * value) % 256
However, this actually has a really interesting edge case where Math.abs(Integer.MIN_VALUE) == Integer.MIN_VALUE
because it overflows.
Instead, use Math.abs
on the result:
Math.abs((randomNo * value) % 256)
I'll also offer some general critique about this function. The names don't really explain what it does. Why generateNo
? No doubt there are many ways to generate an number. I would suggest a more specific name.
The arguments, randomNo
and value
are also problematic. Why does generateNo
care if the first argument is random or not?
Specifying what you want to happen more clearly, and having names that describe those things, may make it easier to think about.
I also suggest, when having issues like this, to break down the steps so you understand what is going on. Something like:
private static int generateNo(int randomNo, int value)
final int product = randomNo * value;
final int result = product % 256;
// Breakpoint or System.out.println here, to understand the values...
return result;
edited Nov 11 at 22:00
answered Nov 11 at 21:22
Yona Appletree
3,49152635
3,49152635
2
NoteMath.abs
can produce a negative result in an unusual case. Also, typically, the result after an integer overflow will be nonsense. In this special case you can use(randomNo*value) & 0xff
.
– Tom Hawtin - tackline
Nov 11 at 21:31
Hah, you're referring to the edge case whereMath.abs(Integer.MIN_VALUE) == Integer.MIN_VALUE
? Never occurred to me, but that's actually pretty funny, and would be an amazing (and totally possible) bug in this case. I'll edit the answer to suggest usingMath.abs
on the result. That's great.
– Yona Appletree
Nov 11 at 21:59
The fact is though, the OP should really just being thinking more about what this function is supposed to do, and probably some research into integer overflow and the modulus operator.
– Yona Appletree
Nov 11 at 22:01
add a comment |
2
NoteMath.abs
can produce a negative result in an unusual case. Also, typically, the result after an integer overflow will be nonsense. In this special case you can use(randomNo*value) & 0xff
.
– Tom Hawtin - tackline
Nov 11 at 21:31
Hah, you're referring to the edge case whereMath.abs(Integer.MIN_VALUE) == Integer.MIN_VALUE
? Never occurred to me, but that's actually pretty funny, and would be an amazing (and totally possible) bug in this case. I'll edit the answer to suggest usingMath.abs
on the result. That's great.
– Yona Appletree
Nov 11 at 21:59
The fact is though, the OP should really just being thinking more about what this function is supposed to do, and probably some research into integer overflow and the modulus operator.
– Yona Appletree
Nov 11 at 22:01
2
2
Note
Math.abs
can produce a negative result in an unusual case. Also, typically, the result after an integer overflow will be nonsense. In this special case you can use (randomNo*value) & 0xff
.– Tom Hawtin - tackline
Nov 11 at 21:31
Note
Math.abs
can produce a negative result in an unusual case. Also, typically, the result after an integer overflow will be nonsense. In this special case you can use (randomNo*value) & 0xff
.– Tom Hawtin - tackline
Nov 11 at 21:31
Hah, you're referring to the edge case where
Math.abs(Integer.MIN_VALUE) == Integer.MIN_VALUE
? Never occurred to me, but that's actually pretty funny, and would be an amazing (and totally possible) bug in this case. I'll edit the answer to suggest using Math.abs
on the result. That's great.– Yona Appletree
Nov 11 at 21:59
Hah, you're referring to the edge case where
Math.abs(Integer.MIN_VALUE) == Integer.MIN_VALUE
? Never occurred to me, but that's actually pretty funny, and would be an amazing (and totally possible) bug in this case. I'll edit the answer to suggest using Math.abs
on the result. That's great.– Yona Appletree
Nov 11 at 21:59
The fact is though, the OP should really just being thinking more about what this function is supposed to do, and probably some research into integer overflow and the modulus operator.
– Yona Appletree
Nov 11 at 22:01
The fact is though, the OP should really just being thinking more about what this function is supposed to do, and probably some research into integer overflow and the modulus operator.
– Yona Appletree
Nov 11 at 22:01
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53253208%2fjava-mod-operator-returns-negative-value%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
2
The multiplication has overflowed integer's range.
– Andy Turner
Nov 11 at 21:07
2
And the modulus operator works like division, so it'll give a negative answer if one argument is negative.
– Yona Appletree
Nov 11 at 21:08