Class: SpinelKit::Hex
- Inherits:
-
Object
- Object
- SpinelKit::Hex
- Defined in:
- lib/spinel_kit/hex.rb
Class Method Summary collapse
-
.byte2(n) ⇒ Object
Int byte 0..255 -> two-char LOWERCASE hex (15 -> “0f”).
-
.nibble(c) ⇒ Object
Hex digit char -> int 0..15, or -1 if not a hex digit (upper or lower).
-
.nibble_char(n) ⇒ Object
Int nibble 0..15 -> single UPPERCASE hex char (“0”..“9”,“A”..“F”).
-
.to_int(s) ⇒ Object
Parse the leading hex digits of ‘s` -> int (“1a3” -> 419).
Class Method Details
.byte2(n) ⇒ Object
Int byte 0..255 -> two-char LOWERCASE hex (15 -> “0f”). (JSON u00XX and similar use lowercase.)
37 38 39 40 41 42 43 |
# File 'lib/spinel_kit/hex.rb', line 37 def self.byte2(n) hex = "0123456789abcdef" out = "" out = out + hex[(n / 16) % 16, 1] out = out + hex[n % 16, 1] out end |
.nibble(c) ⇒ Object
Hex digit char -> int 0..15, or -1 if not a hex digit (upper or lower).
13 14 15 16 17 18 19 20 21 22 23 24 |
# File 'lib/spinel_kit/hex.rb', line 13 def self.nibble(c) if c >= "0" && c <= "9" return c.getbyte(0) - "0".getbyte(0) end if c >= "a" && c <= "f" return c.getbyte(0) - "a".getbyte(0) + 10 end if c >= "A" && c <= "F" return c.getbyte(0) - "A".getbyte(0) + 10 end -1 end |
.nibble_char(n) ⇒ Object
Int nibble 0..15 -> single UPPERCASE hex char (“0”..“9”,“A”..“F”). (RFC 3986 percent-encoding uses uppercase.)
28 29 30 31 32 33 |
# File 'lib/spinel_kit/hex.rb', line 28 def self.nibble_char(n) if n < 10 return ("0".getbyte(0) + n).chr end ("A".getbyte(0) + n - 10).chr end |
.to_int(s) ⇒ Object
Parse the leading hex digits of ‘s` -> int (“1a3” -> 419). Stops at the first non-hex char; returns 0 if there is no leading hex digit. Useful for chunked-transfer sizes and the like.
48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
# File 'lib/spinel_kit/hex.rb', line 48 def self.to_int(s) n = 0 i = 0 len = s.length while i < len v = Hex.nibble(s[i]) if v < 0 return n end n = n * 16 + v i += 1 end n end |