Reputation: 112
I am trying to perform some mathematical calculations in java but the expected result is not getting. Since the same snippet of the code when I run in "C" programme then it works correctly please guide me what is getting wrong in the code.
The value that is getting passed to the function is.
v0=1970012 and v1=1970012 and iterations= 32
The "C" Programme snippet looks something like this
void encipher(uint8_t iterations, uint32_t v0, uint32_t v1)
{
uint8_t i;
int key[]={0x02a4bd14,0x6c753bde,0x4ac819ad,0x6da4a0c4};
uint32_t sum, delta;
sum=0x32d61b8e;
delta=0x9E3779B9;
for (i=0; i < iterations; i++) {
v0 += (((v1 << 4) ^ (v1 >> 5)) + v1) ^ (sum + key[sum & 3]);
sum += delta;
v1 += (((v0 << 4) ^ (v0 >> 5)) + v0) ^ (sum + key[(sum>>11) & 3]);
}
en_result0=v0; en_result1=v1;
}
The en_result0 and en_result1 are the global varaibles and are of the same type as v0 and v1
Similarly the Java snippet code looks something like this.
public static void encipher(int iterations, int v0, int v1)
{
int i;
int key[]={0x02a4bd14,0x6c753bde,0x4ac819ad,0x6da4a0c4};
int sum, delta;
sum=0x32d61b8e;
delta=0x9E3779B9;
for (i=0; i < iterations; i++) {
v0 += (((v1 << 4) ^ (v1 >> 5)) + v1) ^ (sum + key[sum & 3]);
sum += delta;
v1 += (((v0 << 4) ^ (v0 >> 5)) + v0) ^ (sum + key[(sum>>11) & 3]);
}
en_result0=v0; en_result1=v1;
}
Here also the en_result0 and en_result1 are global variables of type int
The answer in "C" programme en_result0=3755627302 and en_result1=3278396279
And
The Answer in "java" Programme en_result0=-1152914223 and en_result1=1706153302
Just not Find where is getting wrong Please Help me to find The solution
Upvotes: 0
Views: 109
Reputation: 36339
You should get the correct results when you replace the >> operator by Java's >>> operator. It does an unsigned right shift, just what the C code achieves with declaring unsigned variables and doing right shifts.
The other operations are harmless and give the same results, no matter if signed or unsigned.
Note that to print the results, you should do something like:
println( ((long) result) & 0xFFFFFFFFL ); // where result is int
or use an appropriate printf format (i.e. print it in hex).
Upvotes: 3
Reputation: 500357
One issue is that the C code is using unsigned integer types, whereas the Java code is using signed types (there are no unsigned integers in Java).
One possibility is to use Java's long
in place of C's uint32_t
. It's signed but is double the width. You may also need to change the types of v0
, v1
, en_result0
and en_result1
to avoid integer overflow.
Upvotes: 2
Reputation: 4671
it is because of the value range of an integer in java.
The int data type is a 32-bit signed two's complement integer. It has a minimum value of > -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive)
use a long
instead of int
Upvotes: 0