# Thread: How Can I Convert Decimal To Hexadecimal

1. Registered User
Join Date
Feb 2006
Posts
8

## Unanswered: How Can I Convert Decimal To Hexadecimal

Hi!!!!!

I'm looking for a SQL FUnction that convert a decimal to Hexadecimal and

Hexadecimal to decimal data.

I know the way to convert for. But not with a SQL Function. certainly I

need to know How to express an Exponential Function.

Thank's.

2. L O S T in Reality
Join Date
Nov 2005
Location
San Francisco, CA
Posts
506
Originally Posted by Vicco
Hi!!!!!

I'm looking for a SQL FUnction that convert a decimal to Hexadecimal and

Hexadecimal to decimal data.

I know the way to convert for. But not with a SQL Function. certainly I

need to know How to express an Exponential Function.

Thank's.
check this...

/* User Defined Function To Convert HexaDecimal Value To Decimal Value
Input: HexaDecimal Value In String Format
Output: Decimal Value
*/
CREATE FUNCTION [dbo].[Fn_HEXCONV] (@HEXVAL as VARCHAR(25)) RETURNS DECIMAL(20,0)
AS BEGIN
/* Declarations Of Variables Two Decimal Values To Store The Intermdeiate & Final Result,
String Value To Store The Hexadecimal Value During The Process,Two Counter Variables*/
DECLARE @position int, @INTVAL INT , @CMDSTR NVARCHAR( 255 ) ,@DECVAL DECIMAL(20,0),@DECVALUE DECIMAL(20,0)
/* Initialising Variables */
SET @position = 1
SET @DECVAL=0
WHILE @position <= DATALENGTH(REVERSE(@HEXVAL)) /* Looping Through The String Until It Reaches The 0th Position */
BEGIN
/* Store The Decimal Value If the Hexa Value is Between A-F */
SET @CMDSTR=CASE UPPER(SUBSTRING(REVERSE(@HEXVAL) ,@position,1)) WHEN 'A' THEN '10' WHEN 'B' THEN '11' WHEN 'C' THEN '12' WHEN 'D' THEN '13' WHEN 'E' THEN '14' WHEN 'F' THEN '15' ELSE SUBSTRING(REVERSE(@HEXVAL) ,@position,1) END
SET @INTVAL=CAST(@CMDSTR as INT) /* Casting The String To Integer */
SET @DECVALUE=@INTVAL
SET @DECVAL=@DECVAL+((@DECVALUE)*POWER(CAST(16 AS BIGINT),@position-1))/* Finding The Corresponding Decimal Value & Adding it To The Result */
SET @position=@position+1 /* Incrementing The Counter */
End
return CAST(@DECVAL as Decimal(20,0)) /* Return The Converted Decimal Value Back */
End
Joydeep
Last edited by rudra; 03-14-06 at 16:07. Reason: correction

3. Resident Curmudgeon
Join Date
Feb 2004
Location
In front of the computer
Posts
15,579
That functionality is built in, you don't need a function for it.
Code:
```DECLARE @d DECIMAL(4)

SET @d = 128

SELECT CAST(@d AS VARBINARY(8)), CAST(0x0400000101000000 AS DECIMAL(4))```
-PatP

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•