Search code examples
mysqlsql-serverhexsql-server-expressbigint

Mysql vs sql express server (HEX -> bigint and bigint -> HEX conversion)


I am new to the SQL express server and trying to convert HEX to bigint and bigint to HEX again. However, I noticed that MySQL and SQL express server calculations give different results.

HEX to bigint:

MySQL:

SELECT CONV('DA346CC793AD1510',16,10);

Output:

15723311803489129744

SQL Express :

SELECT CAST(CONVERT(VARBINARY(MAX), 'DA346CC793AD1510', 2) AS BIGINT); 

Output:

-2723432270220421872

Why MySQL and SQL express servers give different outputs? From a mathematical point of view, it must be the same.

However, bigint to HEX conversion in both MySQL and the SQL express servers give the same result.

MySQL: select conv(column_name,10,16);

SQL Express select FORMAT(column_name,'X');

What is the right way in the SQL express server to convert HEX to bigint and bigint to HEX? Am I missing something?


Solution

  • "Why MySQL and SQL express servers give different outputs? From a mathematical point of view, it must be the same."

    BIGINT upper range is 2 to power 63 - 1:

     9,223,372,036,854,775,807   -- upper range of BIGINT
    15,723,311,803,489,129,744   -- converted "DA346CC793AD1510" value
    

    BIGINT cannot store such value and simply overflows:

    9,223,372,036,854,775,807 -> (overflow) -> starting from the lowest value (-9,223,372,036,854,775,808) + (15,723,311,803,489,129,744 - 9,223,372,036,854,775,807) -> -2,723,432,270,220,421,872