This project has moved. For the latest updates, please go here.

Hex conversion not working?

Feb 9, 2016 at 4:45 AM
Edited Feb 9, 2016 at 5:24 AM
Had trouble evaluating a simple hex expression: 0x20 for instance.
Edited HelperMethods.IsHexStart to this:
if ((ptr >= 0) && (ptr + 2 < str.Length)) // See note below
{
   if (str[ptr] == '-')
      return (str[ptr + 1] == '0' && str[ptr + 2] == 'x');
}
if ((ptr >= 0) && (ptr + 1 < str.Length))
   return (str[ptr] == '0' && str[ptr + 1] == 'x');
return false;
In fact if you leave the first 5 lines out entirely, it then allows you to subtract hex terms from other terms (the '-' gets added as an operator):
if ((ptr >= 0) && (ptr + 1 < str.Length))
   return (str[ptr] == '0' && str[ptr + 1] == 'x');
return false;
Also this doesn't catch uppercase '0X' expressions, which are equally as valid; change comparisons to str.ToUpper()[ptr + 2] == 'X'

Also, call me ignorant, but how can the original code work, with all comparisons with single '&' instead of '&&'? Am I missing something basic with C#, or is this an error?
if ((ptr >= 0) & (ptr + 2 < str.Length))
   return (str[ptr] == '-' & str[ptr + 1] == '0' & str[ptr + 2] == 'x');
if ((ptr >= 0) & (ptr + 1 < str.Length))
   return (str[ptr] == '0' & str[ptr + 1] == 'x');
Thank you for the work you've put into this.
Feb 9, 2016 at 5:15 AM
Also, Adding an expression starting with '-', e.g., '-20', broke it. Fixed by adding this code to Parser.Parse:
else if ((op = _operators.IsOperator(_pstr, ref _ptr)) != null)
{
   /// START NEW CODE
   if ((_pstr[_ptr] == '-') && (lastptr == 0))
   {   // Special case: First character is '-'. Insert a '0' as the first number.
      _tokenQueue.Enqueue(new Token() { Value = 0, IsIdent = true, Type = typeof(Int32)});
   }
   /// END NEW CODE