Convert Integer to HEX string

What is the most elegant way to convert an integer variable to a string? The string should represent the value of the variable in hexadecimal format. The solution should be programmed in ST.

Hi Rainer,

Some time ago I implemented a function that converts from a decimal INTEGER value to an hexadecimal STRING. You can use it if you want. Just add the library to your project from the Toolbox > Existing Library in the Logical View.

Dec2HexStr.zip (2.0 KB)

2023-11-16_10-42-58

I’ve done this before for a BYTE, but I think it can be easily adapted to an integer.
Following is the source code for my function. It uses two inputs: - Value (BYTE), the value you want to convert and - pDest (UDINT), the address, where to store the string. Internally it uses an USINT variable (temp). I hope,this will help you!

FUNCTION ByteToHex

	temp := BYTE_TO_USINT(SHR(Value, 4) AND 16#0F);
	IF (temp < 10) THEN
		brsmemset(pDest, temp + 48, 1);
	ELSE
		brsmemset(pDest, temp + 55, 1);
	END_IF;
	temp := BYTE_TO_USINT(Value AND 16#0F);
	IF (temp < 10) THEN
		brsmemset(pDest + 1, temp + 48, 1);
	ELSE
		brsmemset(pDest + 1, temp + 55, 1);
	END_IF;
	brsmemset(pDest + 2, 0, 1);
	
	ByteToHex := TRUE;

END_FUNCTION

Thanks for your answer. It looks good and it should be easy to adapt to an integer variable.
I think the line
brsmemset(pDest, temp + 55, 1);"
should be
brsmemset(pDest, temp + 65, 1);

Hi Xabier,
I tested “Dec2HexStr”. It works fine, exactly what I am looking for.
THANKS

1 Like

No, 55 is right, because you add temp, which holds the value of a nibble, and is in the relevant case bigger or equal 10.

Hi Christian,
you are right, I am sorry. I noticed it when trying out your example.