Friday, March 30, 2012

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.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

Hope it will help you.
Joydeep ;)|||That functionality is built in, you don't need a function for it.DECLARE @.d DECIMAL(4)

SET @.d = 128

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

No comments:

Post a Comment