Hex to Decimal

Hex to decimal code examples

Eight languages on one page. Type a hex value and switch languages to compare the code and the output.

Go

Output:

Quick reference

LanguageHex to decimalDecimal to hex
Gostrconv.ParseInt(s, 16, 64)strconv.FormatInt(n, 16)
Rustu64::from_str_radix(s, 16)format!("{:x}", n)
PHPhexdec($s)dechex($n)
Rubys.hexn.to_s(16)
Kotlins.toLong(16)n.toString(16)
SwiftInt(s, radix: 16)String(n, radix: 16)
MySQLCONV(s, 16, 10)HEX(n)
PostgreSQLx'FF'::intto_hex(n)

For Python, JavaScript, Java, C, C++, C# and Excel, each language has its own page: Python, JavaScript, Java, C, C++ and C# and Excel.

Hex to decimal code by language

Go

strconv.ParseInt(s, 16, 64) parses a hex string into a signed 64-bit integer and returns an error for bad input.

v, err := strconv.ParseInt("FF", 16, 64)   // 255, <nil>
u, err := strconv.ParseUint("FFFFFFFFFFFFFFFF", 16, 64)   // 18446744073709551615

ParseInt stops at 7FFFFFFFFFFFFFFF. Use ParseUint up to FFFFFFFFFFFFFFFF, or math/big for longer values.

Rust

from_str_radix returns a Result, so the compiler makes you handle bad input.

u64::from_str_radix("FF", 16)    // Ok(255)
i64::from_str_radix("-FF", 16)   // Ok(-255)

The call rejects a 0x prefix and returns Err with InvalidDigit. Overflow returns Err with PosOverflow.

PHP

hexdec() converts a hex string and skips any character that is not a hex digit.

hexdec("FF");     // 255
hexdec("0xFF");   // 255
hexdec("G1");     // 1, with a deprecation notice

Above PHP_INT_MAX (9,223,372,036,854,775,807), hexdec returns a float and loses precision. hexdec("FFFFFFFFFFFFFFFF") returns 1.8446744073709552E+19.

Ruby

String#hex converts a hex string, accepts a 0x prefix and has no size limit.

"FF".hex                    # 255
"0xFF".hex                  # 255
"FFFFFFFFFFFFFFFFFF".hex    # 4722366482869645213695
Integer("FF", 16)           # 255

"G1".hex returns 0 without an error. Integer("G1", 16) raises ArgumentError, so use it when input needs validation.

Kotlin

String.toLong(16) converts a hex string and throws NumberFormatException on bad input.

"FF".toLong(16)        // 255
"FF".toIntOrNull(16)   // 255, or null on bad input

The call rejects a 0x prefix. Values above 7FFFFFFFFFFFFFFF need toULong(16) or BigInteger.

Swift

Int(s, radix: 16) returns an optional, which is nil when the text is not valid hex or does not fit.

Int("FF", radix: 16)                  // Optional(255)
UInt64("FFFFFFFFFFFFFFFF", radix: 16) // Optional(18446744073709551615)

The call rejects a 0x prefix, so remove it first.

MySQL

CONV(s, 16, 10) converts a hex string to a decimal string with 64-bit precision.

SELECT CONV('FF', 16, 10);   -- '255'
SELECT HEX(255);             -- 'FF'

The result is a string, so cast it with CAST(CONV(...) AS UNSIGNED) for arithmetic.

PostgreSQL

A hex bit-string literal casts to an integer, and the cast reads the bits as signed.

SELECT x'FF'::int;            -- 255
SELECT x'FFFFFFFF'::int;      -- -1
SELECT x'FFFFFFFF'::bigint;   -- 4294967295
SELECT to_hex(255);           -- 'ff'

With ::int, values from 80000000 up read as negative. Cast to bigint for 8-digit values. x'FFFFFFFFFFFFFFFF'::bigint returns -1, and 17 or more digits raise an error.

How the languages differ

The 0x prefix, invalid characters and overflow produce different results in each language.

Language0x prefixInvalid characterToo large
GoRejected with base 16, accepted with base 0ErrorError, returns the maximum value
RustRejectedErr(InvalidDigit)Err(PosOverflow)
PHPAcceptedSkipped with a noticeReturns a float
RubyAccepted by hex and to_i(16)hex returns 0, Integer() raisesNo limit
KotlinRejectedNumberFormatExceptionNumberFormatException
SwiftRejectednilnil

Strip the prefix before parsing in Rust, Kotlin and Swift, and validate input in PHP and Ruby, since both accept bad input without stopping.

Write the conversion yourself

Multiply the running total by 16 and add each digit's value, from left to right. This loop is the standard algorithm that every parse function runs, and it suits languages with no built-in.

func hexToDec(s string) (uint64, error) {
	var n uint64
	for _, c := range s {
		var d uint64
		switch {
		case c >= '0' && c <= '9':
			d = uint64(c - '0')
		case c >= 'a' && c <= 'f':
			d = uint64(c-'a') + 10
		case c >= 'A' && c <= 'F':
			d = uint64(c-'A') + 10
		default:
			return 0, fmt.Errorf("invalid hex digit %q", c)
		}
		n = n*16 + d
	}
	return n, nil
}

hexToDec("1A2B") returns 6699 and hexToDec("DEADBEEF") returns 3735928559. The loop has no overflow check, so values past 16 digits wrap around. The same steps work by hand, as shown in how to convert hex to decimal by hand.

Frequently asked questions

How do you convert hex to decimal in code?
Call the language's parse function with base 16. Go uses ParseInt(s, 16, 64), Rust uses from_str_radix(s, 16), Ruby uses s.hex, and PHP uses hexdec(s).
Which languages accept the 0x prefix when parsing?
PHP and Ruby accept it, and Go accepts it only with base 0. Rust, Kotlin and Swift reject it, so remove the prefix before you call them.
Which language has no size limit for hex values?
Ruby, because its integers grow to any size. Go, Rust, Kotlin and Swift stop at 64 bits and need a big-number type beyond that.
Does PHP hexdec return an error for invalid input?
No. hexdec skips characters that are not hex digits and returns the rest as a number. hexdec("G1") returns 1 with a deprecation notice, so check the string before you call it.
How do you convert hex to decimal in SQL?
Use CONV(s, 16, 10) in MySQL and x'FF'::int in PostgreSQL. MySQL returns a string, and PostgreSQL reads values from 80000000 up as negative unless you cast to bigint.