Michaël
Michaël

Reputation: 6734

Convert varchar(32) to bigint

It is possible to convert a varchar(32) (a hexadecimal string like 0x81f2cf442269e111b99c1cc1deedf59c) to a bigint in sql server ?

I have tried this :

select convert(bigint, convert (varbinary(16), '0x81f2cf442269e111b99c1cc1deedf59c', 1))

but I am not sure that it works with higher and lower values.

Upvotes: 1

Views: 1962

Answers (2)

TomTom
TomTom

Reputation: 62127

It is possible to convert a varchar(32) (a hexadecimal string like 0x81f2cf442269e111b99c1cc1deedf59c) to a bigint in sql server ?

2 answers with examples. BOTH fundamentally wrong.

CAN NOT BE DONE. Anyone cares running a basic math check first?

32 hex = 16 bytes. Biging: 8 bytes.

All your code is one thing - useless. You CANNOT convert a 32 hex string with 16 bytes worth of numbers into a 8 byte number. Only in very few cases (upper 8 bytes all 0).

Upvotes: 4

Elias Hossain
Elias Hossain

Reputation: 4469

I hope you can go with below ways, would you please try this.

DECLARE @HexValue Varchar(32)
SET @HexValue = '0x81f2cf442269e111b99c1cc1deedf59c'

Declare @Query NVARCHAR(100)
Declare @Parameters NVARCHAR(50)
Declare @ReturnValue BIGINT

SET @Query = N'Select @Result = Convert(BIGINT,' + @HexValue + ')'
SET @Parameters = N'@Result BIGINT output'
EXEC MASTER.dbo.Sp_executesql @Query, @Parameters, @ReturnValue OUTPUT

SELECT @ReturnValue

Thanks for your time.

Upvotes: 0

Related Questions