Page 1 of 1

Convert char to hex

PostPosted: Wed Apr 17, 2013 6:02 pm
by aimin8828
Dear all:

There was a question as below in my interview, could you please help to have a look how to achieve it? thanks a lot!

Question: How to convert the char variable with 2 bytes into HEX variable with 1 byte? (The input characters is just '0123456789ABCDEF'), for exeample, input is 'AB' and the output is X'AB'.

Re: Convert char to hex

PostPosted: Wed Apr 17, 2013 6:30 pm
by Robert Sample
Method 1:
Use EVALUATE with 256 WHEN statements specified

Method 2:
Use a PIC S9(04) COMP-5 output variable
Redefine the output variable so you can access each byte separately
Use EVALUATE with 16 WHEN statements for the first byte of the input and compute the COMP-5 variable appropriately
Use EVALUATE with 16 WHEN statements for the second byte of the input and compute the COMP-5 variable appropriately
Move the redefined second byte of the COMP-5 variable to your final variable

Method 3:
Use the intrinsic function ORD with appropriate IF logic to convert the bytes of the input variable

These are suggestions -- there are other ways to do the conversion.

Re: Convert char to hex

PostPosted: Wed Apr 17, 2013 6:35 pm
by BillyBoyo
Various ways. For instance, each character represents the values 0-15. 0-9 map to 0-9, A-F map to 10-15.

The first digit is 16 times bigger (number base is 16, remember) than the one on the right.

Add 16 * "value from first character" to "value from second character" storing the result in a binary/comp/comp-4/comp-5 field of two bytes. Redefine the field so that the rightmost byte is PIC X.

DISPLAY that rightmost byte. Presto.

Re: Convert char to hex

PostPosted: Wed Apr 17, 2013 6:53 pm
by aimin8828
BillyBoyo wrote:Various ways. For instance, each character represents the values 0-15. 0-9 map to 0-9, A-F map to 10-15.

The first digit is 16 times bigger (number base is 16, remember) than the one on the right.

Add 16 * "value from first character" to "value from second character" storing the result in a binary/comp/comp-4/comp-5 field of two bytes. Redefine the field so that the rightmost byte is PIC X.

DISPLAY that rightmost byte. Presto.



Dear Robert / BillyBoyo ,Thank you very much for your kind response.

Re: Convert char to hex

PostPosted: Tue Apr 30, 2013 6:40 pm
by Anuj Dhawan
I'm late to the party but I'm beaten up by the statement
for exeample, input is 'AB' and the output is X'AB'.
- did it mean what it says? :? Please assist.

Re: Convert char to hex

PostPosted: Tue Apr 30, 2013 7:04 pm
by Robert Sample
Anuj:

Input would be X'C1C2' ('AB') and output would be X'AB'

Re: Convert char to hex

PostPosted: Wed May 01, 2013 9:58 am
by Anuj Dhawan
That make sense, Thanks Robert.

Thanks for saving me from forgetting all what I learned about HEXADECIMAL during college...! :D