1
0

Constant.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /* vim: set expandtab ts=4 sw=4: */
  2. /*
  3. * You may redistribute this program and/or modify it under the terms of
  4. * the GNU General Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. *
  7. * This program is distributed in the hope that it will be useful,
  8. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. * GNU General Public License for more details.
  11. *
  12. * You should have received a copy of the GNU General Public License
  13. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. var TABLE = {
  16. '0000': '0',
  17. '0001': '1',
  18. '0010': '2',
  19. '0011': '3',
  20. '0100': '4',
  21. '0101': '5',
  22. '0110': '6',
  23. '0111': '7',
  24. '1000': '8',
  25. '1001': '9',
  26. '1010': 'a',
  27. '1011': 'b',
  28. '1100': 'c',
  29. '1101': 'd',
  30. '1110': 'e',
  31. '1111': 'f'
  32. };
  33. var base2ToHex = function (numStr) {
  34. while ((numStr.length / 4) % 1) { numStr = '0' + numStr; }
  35. var out = [];
  36. for (var i = 0; i < numStr.length; i += 4) {
  37. out.push(TABLE[numStr.substring(i, i+4)]);
  38. }
  39. return out.join('');
  40. };
  41. var testBase2 = function () {
  42. for (var i = 0; i < 10000; i++) {
  43. var num = Math.random() * 4294967296;
  44. var b2 = num.toString(2);
  45. var numB = Number('0x' + base2ToHex(b2));
  46. if (num !== numB) { throw new Error(num + " --> " + b2 + " --> " + numB); }
  47. }
  48. };
  49. var base2 = module.exports.base2 = function (numStr) {
  50. var type = "uint8_t";
  51. if (numStr.length > 8) { type = "uint16_t"; }
  52. if (numStr.length > 16) { type = "uint32_t"; }
  53. if (numStr.length > 32) { type = "uint64_t"; }
  54. if (numStr.length > 64) { throw new Error("cannot have more than 64 bits"); }
  55. return '((' + type + ') 0x' + base2ToHex(numStr) + ((type === 'uint64_t') ? 'ull' : 'ul') + ')';
  56. };
  57. var rand64 = module.exports.rand64 = function () {
  58. return '((uint64_t) 0x' +
  59. (Math.random().toString(16) + Math.random().toString(16)).replace(/0\./g, '') + 'ull)';
  60. };
  61. var rand32 = module.exports.rand32 = function () {
  62. return '((uint32_t) 0x' + Math.random().toString(16).replace(/0\./g, '') + 'ul)';
  63. };
  64. var randHexString = module.exports.randHexString = function (lenStr) {
  65. var hex = '';
  66. var len = Number(lenStr);
  67. while (hex.length < len) { hex += Math.random().toString(16).substring(2); }
  68. return '"' + hex.substring(0,len) + '"';
  69. };
  70. if (!module.parent) {
  71. console.log("testing " + __filename);
  72. testBase2();
  73. }