Reputation: 3
I have 4 bytes:
Byte_0=0x31
Byte_1=0x32
Byte_2=0x33
Byte_3=0x34
And I would like to get a word_1=0x1234, where 1 is the conversion from hex to ASCII. Any ideas about how to get this?
Upvotes: 0
Views: 2982
Reputation: 3080
In addition to previous suggestion there is another way to convert string to integer and bytes to string.
PROGRAM PLC_PRG
VAR
arBt : ARRAY[1..4] OF BYTE := [16#31, 16#32, 16#33, 16#34];
pstrString : POINTER TO STRING(4);
iInt : INT;
END_VAR
pstrString := ADR(arBt); // now pstrString^ is equal to "1234"
iInt := STRING_TO_INT(pstrString^); // now iInt = 1234 number
END_PROGRAM
If you have Codesys 2.3 then delete [
brackets in [16#31, 16#32, 16#33, 16#34]
.
Upvotes: 2
Reputation: 514
There may be an internal function available to translate an ASCII text digit to its numerical value, but you can easily write one yourself:
FUNCTION Ascii_To_Byte : WORD
VAR_INPUT ascii : BYTE
IF ascii>=16#30 AND ascii<=16#39 THEN // range 0-9
Ascii_To_Byte := ascii - 16#30;
ELSIF ascii>=16#41 AND ascii<=16#46 THEN // range A-F
Ascii_To_Byte := ascii - 16#41 + 16#0A;
ELSE
Ascii_To_Byte := -1 // error condition, invalid input
Then it's just a matter of converting the values and bit shifting:
word_1 := SHL(Ascii_To_Byte(Byte_0), 12) + SHL(Ascii_To_Byte(Byte_1), 8) + SHL(Ascii_To_Byte(Byte_2), 4) + Ascii_To_Byte(Byte_3)
(Code written in TwinCAT, may be slightly different in Codesys.)
Upvotes: 0