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. (2.0 KB)


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!


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


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.

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.