Solved

Convert HEX to ASCII - TSQL

Posted on 2013-12-09
16
8,349 Views
Last Modified: 2013-12-15
Hello Experts,

I am trying to write a query to convert Hexadecimal record into ASCII. I have this below query, but I want to apply this query to a table to populate a new field.

declare @v varchar(200), @sql nvarchar(MAX), @ch varchar(200)
select @v = '35323139636430323030303030303030306130393031623332333339303030323b30313631363132363030303230303431'
select @sql = 'SELECT @ch = convert(varchar, 0x' + @v + ')'
EXEC sp_executesql @sql, N'@ch varchar(30) OUTPUT', @ch OUTPUT
SELECT @ch AS ConvertedToASCII

Open in new window


I have a table with few columns. One column is basically a varchar(200) and it has hexadecimal values. I want to populate another column with ASCII values in the same table based on the hexadecimal column.

Can someone please help me with the query.
0
Comment
Question by:ravichand-sql
  • 4
  • 3
  • 3
  • +4
16 Comments
 

Author Comment

by:ravichand-sql
Comment Utility
I have tried the below solution..

SELECT convert(varchar, 0x'Hex value')

Open in new window


But this is working only for a single record. How to modify the above query, if I want to use a column instead ?
0
 
LVL 15

Expert Comment

by:JimFive
Comment Utility
Did you try
SELECT Convert(varchar, 0x+<columnName>)
0
 
LVL 32

Expert Comment

by:Daniel Wilson
Comment Utility
What about ...
Update MyTable set strField = convert(varchar(64), hexField,0);

http://social.msdn.microsoft.com/Forums/sqlserver/en-US/6bfe99c8-c662-44bf-ae10-74b4a00d4da7/hex-to-string?forum=transactsql
for more options / discussion
0
 
LVL 15

Expert Comment

by:JimFive
Comment Utility
I think I don't understand the question.  In your example, everything is already ASCII, there are no numeric types referenced.

Can you give a simple example:
What would you expect to see for an input value of CF?
0
 

Author Comment

by:ravichand-sql
Comment Utility
Hi Jim,

The query you posted in your first comment is not working. I tried that too..

Here is the input: 3532393263326265303030303030303030613064366336383233333630303032

Output should be: 5292c2be000000000a0d6c6823360002
0
 
LVL 32

Expert Comment

by:Daniel Wilson
Comment Utility
So you're actually trying to convert ASCII to Hex, not Hex to ASCII?
0
 
LVL 29

Expert Comment

by:Göran Andersson
Comment Utility
You can create a function for converting hex to ASCII:

create function HexToAscii(@hex varchar(max))
returns varchar(max)
as
begin
	declare @result varchar(max) = '', @i int = 1, @c int
	while @i < len(@hex) begin
		set @c = (charindex(substring(@hex,@i,1), '0123456789abcdef') - 1) * 16 + charindex(substring(@hex,@i+1,1), '0123456789abcdef') - 1
		set @result = @result + char(@c)
		set @i = @i + 2
	end
	return @result
end

Open in new window


Then you can use that in the query to convert the value from each record:

update TheTable
set TextValue = dbo.HexToAscii(HexValue)

Open in new window

0
 
LVL 15

Expert Comment

by:JimFive
Comment Utility
For this solution you need a table called Numbers with a column called Number that contains the numbers from 1 to the max length of your conversion field.

This works for a single value.  For a table you will need to adjust the select statement to include your key field as well as to correlate the subquery.

DECLARE @x as varchar(MAX)
Set @x = '35323139636430323030303030303030306130393031623332333339303030323b30313631363132363030303230303431'

SELECT @x, (select CHAR(LEFT(SUBSTRING(@x,Number,2),1)*16+RIGHT(Substring(@X,Number,2),1))
                   FROM Numbers
                   WHERE number > 0 and number < Len(@x) and number%2 = 1
                   ORDER BY Number
                   FOR XML PATH('')) fixed

Open in new window

0
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 
LVL 15

Accepted Solution

by:
dbbishop earned 167 total points
Comment Utility
See this solution

Use:
UPDATE myTable
SET newColumn = dbo.HexToStr(CONVERT(NVARCHAR(MAX), myColumn, 2))
0
 
LVL 15

Assisted Solution

by:JimFive
JimFive earned 167 total points
Comment Utility
I had a little more time to work on this so this will return a recordset, you'll need to fill in your actual table and column names.

SELECT ST1.Key, ST1.VAL, (select CHAR(LEFT(SUBSTRING(ST2.VAL,Number,2),1)*16+RIGHT(Substring(ST2.VAL,Number,2),1))
                   FROM SourceTable ST2, Numbers
                   WHERE ST2.Key = ST1.Key
                   AND number > 0 and number < Len(ST2.VAL) and number%2 = 1
                   ORDER BY Number
                   FOR XML PATH('')) fixed
FROM SourceTable ST1

Open in new window


To use in an update Statement
UPDATE SourceTable
SET asciiValue = (select CHAR(LEFT(SUBSTRING(ST2.VAL,Number,2),1)*16+RIGHT(Substring(ST2.VAL,Number,2),1))
                   FROM SourceTable ST2, Numbers
                   WHERE ST2.Key = SourceTable.Key
                   AND number > 0 and number < Len(ST2.VAL) and number%2 = 1
                   ORDER BY Number
                   FOR XML PATH(''))

Open in new window

0
 
LVL 42

Assisted Solution

by:EugeneZ
EugeneZ earned 166 total points
Comment Utility
just try

declare @sql varchar(max)
 select @sql = '3532393263326265303030303030303030613064366336383233333630303032'

 SELECT convert(varchar(max),  convert(varbinary(max),@sql,2) )

--result
--5292c2be000000000a0d6c6823360002
------------------------------------------------------------------------------------------------------------
---or just directly

SELECT convert(varchar(max),  convert(varbinary(max),'3532393263326265303030303030303030613064366336383233333630303032',2) )

--result
--5292c2be000000000a0d6c6823360002

Open in new window


<I want to populate another column with ASCII values in the same table based on the hexadecimal column.>

just as per above post

update yourtable
set strCol=convert(varchar(max),  convert(varbinary(max),hexCol,2) )
where somecol='something'
0
 
LVL 23

Expert Comment

by:Christopher Kile
Comment Utility
BTW, you're converting a decimal number to a hexadecimal number.  ASCII doesn't come anywhere near this entire concept.
0
 
LVL 29

Expert Comment

by:Göran Andersson
Comment Utility
cpkilekofp, the input string is the hexadecimal representation of the ASCII characters that form the output string.

The input just looks like it's decimal because it happens to lack any components over 9, and the output is not a hexadecimal number, it's a string that just happens to be the hexadecimal representation of a number.
0
 
LVL 23

Expert Comment

by:Christopher Kile
Comment Utility
This post is not truly relevant to the topic at hand and may be deleted by adminstrative personnel with prejudice on my part if it is deemed too far off-topic.

GreenGhost,

You said:
cpkilekofp, the input string is the hexadecimal representation of the ASCII characters that form the output string.

That is clearly not true.  If it were true, each ASCII character in the input string would be represented by two hexadecimal digits in the output string, making it twice the size of the input string.  

On the other hand, an ASCII string containing a decimal number will convert to a SHORTER ASCII string if the output string is considered to be a hexadecimal representation of the decimal number in the original string unless it is padded with zeroes.  

This is easily demonstrated:  decimal and hex 0 through 9 are the same length; decimal 10 is length 2 while the corresponding hex value A is of length 1; decimal 100 of length 3 is longer than hex 64; I'll skip a formal proof here, but the decimal length will always be greater than or equal to the hex length.

The example given of a correct output string is considerably shorter than the input.  Therefore, it cannot be a conversion of its ASCII characters to a hexadecimal representation, but must more reasonable be assumed to be a conversion of a decimal number to its hexadecimal representation.
0
 
LVL 29

Expert Comment

by:Göran Andersson
Comment Utility
cpkilekofp, you have it backwards.

The input is the hexadecimal representation of the ASCII codes for the characters in the output, not the other way around.

It's easy to see that this is the correct way to convert the data if you actually try to do the conversion of the example data.
0
 

Author Closing Comment

by:ravichand-sql
Comment Utility
Thank you everyone for spending time on my req. I really appreciate your effort. Thanks a lot.
0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

INTRODUCTION: While tying your database objects into builds and your enterprise source control system takes a third-party product (like Visual Studio Database Edition or Red-Gate's SQL Source Control), you can achieve some protection using a sing…
In SQL Server, when rows are selected from a table, does it retrieve data in the order in which it is inserted?  Many believe this is the case. Let us try to examine for ourselves with an example. To get started, use the following script, wh…
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now