Advertisement
plirof2

Generate hash 0-99 from a string in javascript

Jan 10th, 2024 (edited)
957
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. PHP- + Javascript
  2. You can generate a hash ranging from 01-99 from a string in JavaScript.
  3.  
  4. Here's an example of how you can achieve this using the built-in `hashCode` function:
  5.  
  6. ```javascript
  7. function hashCode(str) {
  8.  let hash = 0;
  9.  for (let i = 0; i < str.length; i++) {
  10.    hash = (hash << 5) - hash + str.charCodeAt(i);
  11.    hash &= hash; // Convert to 32bit integer
  12.  }
  13.  return Math.abs(hash) % 100; // Get a positive number within 0-99 range
  14. }
  15.  
  16. const str = "example";
  17. const hash = String(hashCode(str)).padStart(2, "0");
  18. console.log(hash); // Output: 36
  19. ```
  20.  
  21. In the above example, the `hashCode` function calculates a hash code for the given string. By applying `% 100` to the hash, we get a positive number within the 0-99 range. The `String.padStart(2, "0")` function is used to ensure a consistent two-digit format.
  22.  
  23. ---------------------------------------------------
  24. You can generate a hash ranging from 01-99 from a string in PHP using various hash algorithms. One common algorithm is MD5, which generates a 32-character hexadecimal hash. You can then convert this hash into a decimal value and limit it between 01-99 using modulus division.
  25.  
  26. Here's an example code snippet to illustrate this process:
  27.  
  28. ```php
  29. $string = "example string";
  30. $hash = md5($string); // Generating MD5 hash
  31.  
  32. $decimalHash = hexdec($hash); // Converting hexadecimal hash to decimal
  33.  
  34. $range = $decimalHash % 99; // Getting the remainder after dividing by 99
  35.  
  36. $finalHash = str_pad($range, 2, "0", STR_PAD_LEFT); // Pad the hash with leading zeros if necessary
  37.  
  38. echo $finalHash; // Output: a hash ranging from 01-99
  39. ```
  40.  
  41. Please note that generating a hash using MD5 is not considered secure for cryptographic purposes. If you require more secure hashing, consider using algorithms like SHA-256 or bcrypt.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement