| 1 |
namespace Xmpp.Util { |
| 2 |
|
| 3 |
/** |
| 4 |
* Parse a number from a hexadecimal representation. |
| 5 |
* |
| 6 |
* Skips any whitespace at the start of the string, parses as many valid |
| 7 |
* characters as hexadecimal digits as possible (possibly zero) and returns |
| 8 |
* them as an integer value. |
| 9 |
* |
| 10 |
* ``` |
| 11 |
* // 0xa |
| 12 |
* print("0x%lx\n", from_hex("A quick brown fox jumps over the lazy dog.")); |
| 13 |
* ``` |
| 14 |
*/ |
| 15 |
|
| 16 |
public long from_hex(string numeral) { |
| 17 |
long result = 0; |
| 18 |
bool skipping_whitespace = true; |
| 19 |
foreach (uint8 byte in numeral.data) { |
| 20 |
char c = (char)byte; |
| 21 |
if (skipping_whitespace && c.isspace()) { |
| 22 |
continue; |
| 23 |
} |
| 24 |
skipping_whitespace = false; |
| 25 |
int digit; |
| 26 |
if ('0' <= c && c <= '9') { |
| 27 |
digit = c - '0'; |
| 28 |
} else if ('A' <= c && c <= 'F') { |
| 29 |
digit = c - 'A' + 10; |
| 30 |
} else if ('a' <= c && c <= 'f') { |
| 31 |
digit = c - 'a' + 10; |
| 32 |
} else { |
| 33 |
break; |
| 34 |
} |
| 35 |
result = (result << 4) | digit; |
| 36 |
} |
| 37 |
return result; |
| 38 |
} |
| 39 |
|
| 40 |
} |