# Conversion From Hex To Decimal

Dear Experts,

I have a code from #C from hex data type as follow

0x01 that will read in serial port as 01

How do you convert that into abap code?

DATA: x type i.

x = cl_abap_codepage=>convert_to( '0x02' )

The expected result should be 2

but I get 813183026

Thanks,

Sam

10|10000 characters needed characters exceeded

### Related questions

Posted on Nov 01, 2019 at 12:58 PM

To convert one byte containing FF hexadecimal value (decimal 255) into an integer variable:

```DATA: byte    TYPE x LENGTH 1,
integer TYPE i.

byte = 'FF'.
integer = byte.
ASSERT integer = 255.```
• Target i, (b,s) : Only the last 4 bytes of the source field are converted. If the source field is shorter than 4 bytes, it is made longer on the left with the hexadecimal 0 until it is 4 bytes long. The content of these bytes is interpreted as a number stored in big endian order, of type i. The hexadecimal values from "00000000" to "7FFFFFFF" are assigned to numbers from +0 to +2147483647 and the hexadecimal values from "80000000" to "FFFFFFFF" are assigned to the numbers -2147483648 to -1. The numbers obtained in this way are converted in the internal representation of the corresponding integer.

The writing "0x..." is interpreted by ABAP as two characters with no special meaning.

If you want to express a byte value:

```DATA byte TYPE x LENGTH 1.
byte = 'FF'. " the two characters FF are interpreted as hexadecimal because byte has type X
DATA(byte_string) = CONV xstring( 'FF00FF00' ). " 4 bytes / interpreted as hexa because type XSTRING```

For more information: ABAP documentation - Conversion Rules for Elementary Data Objects

The method CONVERT_TO of cl_abap_codepage converts a text ('0x02' are four characters) into bytes, by using the encoding parameter whose default is UTF-8 (in your case all four characters are part of US-ASCII, so it's four bytes, '30783032' in hexadecimal notation).

But you transfer it to an integer variable, so the standard conversion rule from X to I applies (see explanation in the link above) which gives 813183026 (as you can see in the Windows Calculator in Programmer mode: press "HEX", type "30783032", and you see "813 183 026" at the right of "DEC"). Note that SAP could also have given "842 037 296" if your system was of type Little Endian.