ChainsBoy

Squirrel hexToInteger function

Aug 26th, 2016
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.70 KB | None | 0 0
  1. /**
  2.  * Convert hex string to an integer
  3.  * Credits: https://forums.electricimp.com/discussion/comment/2877/#Comment_2877
  4.  * @param hex  The hex to convert.
  5.  * @return int
  6.  */
  7. function hexToInteger (hex) {
  8.     local result = 0;
  9.     local shift = hex.len() * 4;
  10.  
  11.     // For each digit..
  12.     for (local d = 0; d < hex.len(); d++) {
  13.         local digit;
  14.  
  15.         // Convert from ASCII Hex to integer
  16.         if (hex[d] >= 0x61)
  17.             digit = hex[d] - 0x57;
  18.         else if (hex[d] >= 0x41)
  19.              digit = hex[d] - 0x37;
  20.         else
  21.              digit = hex[d] - 0x30;
  22.  
  23.         // Accumulate digit
  24.         shift -= 4;
  25.         result += digit << shift;
  26.     }
  27.  
  28.     return result;
  29. }
Advertisement
Add Comment
Please, Sign In to add comment