I'm trying to subtract one byte from another while making sure no overflow happens, but get unexpected results.
In the following code, I expect data2 array to be subtracted from data1 array. However I get low values when I am sure there should be high ones.
for (int i = 0; i < data1.length; i++) {
if (data1[i] > data2[i]) {
dest[i] = (byte) (data1[i] - data2[i]);
} else {
dest[i] = 0;
}
}
I figured I should make sure data2 byte isn't negative and being added to data1. So I came to:
for (int i = 0; i < data1.length; i++) {
if (data1[i] > data2[i]) {
dest[i] = (byte) (data1[i] & 0xff - data2[i] & 0xff);
} else {
dest[i] = 0;
}
}
However this also doesn't give the right results.
I hope I'm doing something stupidly wrong here, or my problem resides somewhere else of which I can't figure out where.
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire