Skip to content

Instantly share code, notes, and snippets.

@jcdickinson
Created October 4, 2018 05:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jcdickinson/9a4205287ae107e9f4e5f6764f432db9 to your computer and use it in GitHub Desktop.
Save jcdickinson/9a4205287ae107e9f4e5f6764f432db9 to your computer and use it in GitHub Desktop.
hextoint
// Does not reject invalid data. define NO_OVERFLOW to avoid values
// larger than 15, but it will still accept invalid characters.
// MSN(x) = Most-significant nibble
// LSN(x) = Least-significant nibble
// SHL(x, y) = Shift left
// SHR(x, y) = Shift right
// MSN(Digits) = 0011
// MSN(Upper) = 0100
// MSN(Lower) = 0110
// LSN(0) = 0000, LSN(9) = 1001
// LSN(a|A) = 0001, LSN(f|F) = 0110
uint8_t hextoint(uint8_t c)
{
// =1 for Upper/Lower, =0 for Digit
// SHR(a, 6) = SHR(0110 0001, 6) = 0000 0001
uint8_t ms = (c >> 6);
#ifdef NO_OVERFLOW
ms &= 0b0001; // MSB may be set
#endif
// =9 for Upper/Lower, =0 for Digit
// LSN(Upper/Lower) is one too large, otherwise we'd use 10 (a/A = 10)
// SHL(0001, 3) | 0001 = 1000 | 0001 = 1001
uint8_t nine = (ms << 3) | ms;
// Extract LSN, which is still 1 too large for Alpha/alpha
c &= 0xF;
#ifdef NO_OVERFLOW
c ^=
// for g, c = 0111 = 7
// SHR(0111, 1) = 0011
// SHL(0111, 1) = 1110
// 0111 AND 0010 = 0010
// ----
// AND = 0010
// XOR c = 0101 = 5
((c >> 1) & (c << 1) & (c & 0x2))
// for h, c = 1000 (and nine = 1001) = 17
// SHL(ms, 3) = 1000
// AND c = 1000
// XOR c = 0000
| ((ms << 3) & c);
#endif
return c + nine;
}
uint8_t hextoint(uint8_t c1, uint8_t c2)
{
return (hextoint(c1) << 4) | hextoint(c2);
}
@Luuut
Copy link

Luuut commented Dec 23, 2023

uint8_t hextoint(uint8_t c)
{
// =1 cho Trên/Dưới, =0 cho Chữ số
// SHR(a, 6) = SHR(0110 0001, 6) = 0000 0001
uint8_t ms = (c >> 6);
#ifdef KHÔNG_TRÀN
ms &= 0b0001; // MSB có thể được đặt
#kết thúc

// =9 cho Trên/Dưới, =0 cho Chữ số
// LSN(Upper/Lower) là một cái quá lớn, nếu không chúng tôi sẽ sử dụng 10 (a/A = 10)
// SHL(0001, 3) | 0001 = 1000 | 0001 = 1001
uint8_t chín = (ms << 3) | ms;

// Trích xuất LSN, vẫn còn 1 quá lớn đối với Alpha/alpha
c &= 0xF;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment