Skip to content

Conversation

spirinvladimir
Copy link
Contributor

Optimize Hexadecimal Validation Logic

Problem: Original logic performed redundant comparisons regardless of ASCII value ordering.

Solution: Restructured validation to follow ASCII sequence (0-9: 48-57, A-F: 65-70, a-f: 97-102):

if (ch < '0') return 0;           // < 48: Invalid
if (ch <= '9') continue;          // 48-57: Valid digits
if (ch < 'A') return 0;           // 58-64: Invalid gap  
if (ch <= 'F') continue;          // 65-70: Valid A-F
if (ch < 'a') return 0;           // 71-96: Invalid gap
if (ch <= 'f') continue;          // 97-102: Valid a-f
return 0;                         // > 102: Invalid

Benefits:

  • Eliminates redundant range checks
  • Reduces comparisons from 6 to 2-3 per character
  • Early exit on invalid characters
  • Follows natural ASCII ordering for better branch prediction

@mhw0 mhw0 merged commit 97fde90 into mhw0:dev Aug 29, 2025
2 checks passed
@mhw0
Copy link
Owner

mhw0 commented Aug 29, 2025

Hi @spirinvladimir, merged. Thanks for the PR!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants