Skip to content

Convert string to int, hex or binary number

SystemVerilog string methods allow you to convert strings to a int, hex, binary or real data type.

Main thing to keep in mind is:

The conversion scans all leading digits and underscore characters ( _ ) and stops as soon as it encounters any other character or the end of the string. It returns zero if no digits were encountered.

In this example, the string "1024" is converted into various integral data types. You can see the above with str.atobin(), the scanning stops after the leave 10 since 2 is not a binary digit.

s = "1024";
/* Output: atoi 1024 */
$display("atoi %0d", s.atoi());

/* Output: atohex 0x1024 (4132)*/
$display("atohex 0x%0x (%0d)", s.atohex(), s.atohex());

/* Output: atobin 0b10 (2) */
$display("atobin 0b%0b (%0d)", s.atobin(), s.atobin());

/* Output: atooct 0o1024 (532) */
$display("atooct 0o%0o (%0d)", s.atooct(), s.atooct());

/* Output: atoreal 1024.500000 */
s = "1024.5";
$display("atoreal %0f", s.atoreal());
atoi 1024
atohex 0x1024 (4132)
atobin 0b10 (2)
atooct 0o1024 (532)
atoreal 1024.500000