On Feb 7, 7:40 pm, beach...@gmail.com wrote:
> Hi,
>
> I'm trying to implement a simple hash algorith called rs_hash in
> javascript,
> but I cannot get a correct result.
>
> In c the code looks like this:
>
> signed char myArray[6];
>
> myArray[0]= 0x01;
> myArray[1]= 0x02;
> myArray[2]= 0x03;
> myArray[3]= 0x04;
> myArray[4]= 0x05;
> myArray[5]= 0x06;
>
> signed int b = 378551;
> signed int a = 63689;
> signed int hash = 0;
> int i= 0;
> int len= 6;
>
> for( i= 0; i<len; i++ )
> {
> hash = hash * a + myArray[i];
> a = a * b;
> }
>
> return hash;
>
> and my try in javascripts looks like this
>
> var myArray = new Array();
>
> myArray[0] = 0x01;
> myArray[1] = 0x02;
> myArray[2] = 0x03;
> myArray[3] = 0x04;
> myArray[4] = 0x05;
> myArray[5] = 0x06;
>
> var b = 378551;
> var a = 63689;
> var hash = 0;
> var i = 0;
> var len= 6;
>
> for( i== 0; i<len; i++)
> {
> hash = hash * a + myArray[i];
> a = a * b;
> }
>
> return hash;
>
> The c functions returns -1596271655 (2698695641 when casted to
> unsigned)
> while the the javacsript funtion returns 4.922527108004972e+107
>
> I guess this has to do with the fact that javascript has typeless
> variables, but is there a way to
> cast them to signed integers?
As it was pointed out, the problem is with your C code, not with
JavaScript.
signed int holds values from -2,147,483,648 to 2,147,483,647 and your
calculations are going way beyond this border. It is called "type
overflow" and the exact error correction is not defined in C language
specifications. It means that depending on particular C/C++ compiler
you may get different results. As I can tell on your current C
compiler type overflow is resolved by simply truncating extra bits, so
from some point your hash = hash * a starts acting as some very fancy/
weird bitwise shift statement. If you are getting the needed results
with it then it is a very lucky coincidence.
In JavaScript all numbers are - at least officially - IEEE-754
floating point double precision, so even after 2,147,483,647 your hash
just keeps growing.
P.S. After you bring your C code into correct form and start porting
in JavaScript, keep in mind some important limits for big integers
summarized in Nielsen's table
<
http://groups.google.com/group/comp....avascript/msg/
3833df1762d81fee>