Binary and hex signed validation [message #1152060] |
Wed, 23 October 2013 19:58 |
Tom Mealey Messages: 7 Registered: October 2013 |
Junior Member |
|
|
Hi all,
I am trying to validate hex and binary input, but the problem I have is that I want to interpret the numbers as signed (2's complement) in some cases, and unsigned in other cases, depending on the context. The relevant grammar looks like this:
ValueRef:
ref=[Macro] | value = (SIGNED_INT | HEX | BINARY)
;
Macro:
name=ID '=' value=(SIGNED_INT | HEX | BINARY)
;
terminal fragment DIGIT: ('0'..'9');
terminal SIGNED_INT returns ecore::EIntegerObject:
'-'* DIGIT*;
terminal fragment HEX_DIGIT: (DIGIT|'a'..'f'|'A'..'F');
terminal HEX returns ecore::EIntegerObject:
'0x' HEX_DIGIT*;
terminal fragment BINARY_DIGIT: ('0' | '1');
terminal BINARY returns ecore::EIntegerObject:
'0b' (BINARY_DIGIT('_')*)*;
I then have a value converter that uses the Java Integer.parseInt to convert each of the three rules into an integer value. My validator performs a check on each ValueRef object, making sure its value is within the expected range for the object's context. However, I am running into difficulties with hex and binary input, because they are always parsed as unsigned values. For the case where I expect a signed value, this becomes a problem.
For example, if I expect a 4-bit signed value, then anywhere within the range {-8,7} works fine. In this context, I want to interpret 0b1111 and 0xf as -1, rather than 15, but I have no way of telling them apart from regular base 10 input. I need to somehow determine if the raw input was a hex or binary string, and then handle it differently in the validation logic. Is this at all possible, to grab the "raw" input for use in validation? Or am I better off going a different route? Thanks for any input or suggestions you have.
Here is the check I perform in my validator, if it helps:
def Boolean checkValueInRange (int value, int nBits, Boolean isSigned) {
if (isSigned) {
if (value < 0) return checkValueInRange(Math.abs(value)-1,nBits-1,false)
else return checkValueInRange(value,nBits-1,false)
}
if (value < 0)
return false
return (value < Math.pow(2,nBits))
}
Cheers,
Tom
|
|
|
|
|
|
Powered by
FUDForum. Page generated in 0.07395 seconds