# JS校验和

`02FD 1000 2322 4978 0140 00AF 6000 0000 0000 F9` (checksum `F9`)

`02FD 1000 D82E 4F76 0189 00AF FA14 0000 0000 E4` (checksum `E4`)

bdicta

JavaScript中的校验和计算 在默认情况下数字为双浮点数的语言中进行整数位数学运算可能会非常困难。您的代码必须确保数字保留为整数，甚至可能保持无符号且在特定的位范围（16位，32位）内。这些额外的步骤可能会使事情复杂化。

``````var hasTyped = (function() {
if(!('Uint8Array' in window)) {
return false;
}

try {
var a = new window.Uint8Array(10);
a[0] = 100;
if(a[0] === 100) {
return true;
}
return false;
} catch (e) {
return false;
}
}());
``````

BSD16 这是一个非常简单的代码，此算法只需要一点点代码。 BSD Checksum算法！

``````(function() {
'use strict';

if(typeof(window.Checksum) === "undefined") {
throw "The Checksum class is required for this code.";
}

/**
* Initialize anything you want in the constructor, such as setting up a lookup
* table of bytes. Make sure to cache your calculations, so they only have to be
* done once.
*/
var BSD16 = function BSD16() {
this.init = 0;
};

/**
* bsd16 for arrays, each value must be numeric and will be bound to 8-bits (Int8Array or Uint8Array works best!)
* @param   {Array}  a input (8-bit array)
* @param   {Number} p previous checksum state
* @returns {Number} new checksum state
*/
BSD16.prototype.array = function(a, p) {
var c = p || 0, i = 0, l = a.length;
for(; i < l; i++) c = (((((c >>> 1) + ((c & 1) << 15)) | 0) + (a[i] & 0xff)) & 0xffff) | 0;
return c;
};

/**
* bsd16 for a single value, update a checksum with a new byte
* @param   {Number} b byte (0-255)
* @param   {Number} p previous checksum state
* @returns {Number} new checksum state
*/
BSD16.prototype.single = function(b, p) {
var c = p || 0;
return (((((c >>> 1) + ((c & 1) << 15)) | 0) + (b & 0xff)) & 0xffff) | 0;
};

Checksum.registerChecksum("bsd16", BSD16);
}());
``````

FNV32（FNV-0和FNV-1）

``````(function() {
'use strict';

if(typeof(window.Checksum) === "undefined") {
throw "The Checksum class is required for this code.";
}

var prime = 0x01000193;

/**
* Initialize anything you want in the constructor, such as setting up a lookup
* table of bytes. Make sure to cache your calculations, so they only have to be
* done once.
*/
var FNV32 = function FNV32() {
this.init = 2166136261; // fnv-1!
};

/**
* The setup method which will be called when new Checksum("fletcher", ...) is called.
* This method is supposed to initialize the checksum cipher and to recieve parameters
* from the constructor.
*
* @param {Number} mode the FNV32 mode (FNV-1 (defualt) or FNV-0)
*/
FNV32.prototype.setup = function(mode) {
if(mode === 0) {
this.init = 0; // fnv-0.
}
};

FNV32.prototype.array = function(a, p) {
var len = a.length,
fnv = p || this.init;

for(var i = 0; i < len; i++) {
fnv = (fnv + (((fnv << 1) + (fnv << 4) + (fnv << 7) + (fnv << 8) + (fnv << 24)) >>> 0)) ^ (a[i] & 0xff);
}

return fnv >>> 0;
};

FNV32.prototype.single = function(b, p) {
var fnv = p || this.init;
return ((fnv + (((fnv << 1) + (fnv << 4) + (fnv << 7) + (fnv << 8) + (fnv << 24)) >>> 0)) ^ (b & 0xff)) >>> 0;
};

Checksum.registerChecksum("fnv32", FNV32);
}());
``````