TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
 Specialized Dev Zones Research Center eBook Library .NET Java C++ Web Dev Architecture Database Security Open Source Enterprise Mobile Special Reports 10-Minute Solutions DevXtra Blogs Slideshow

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

 Home » Tip Bank » Database Development » SQL » Transact-sql
Language: SQL Server
Expertise: Beginner
Nov 30, 1999

### WEBINAR:On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning

# T-SQL Data Conversion

Question:
I want to convert a signed integer into a 16-bit binary as part of a SELECT statement. For example:
select myint, howeveritsdone as Binary
from mytable

myint  Binary
----   ----------------
-137   1111111101110111
-100   1111111110011100
How can I do this?

The kernel of the solution is that 16 is 2 to the fourth power. Each position in the hex string can be translated into four binary digits to create the final result. To do this, create a lookup table of the following structure and data:

cHex   cBin
0      0000
1      0001
2      0010
3      0011
4      0100
5      0101
6      0110
7      0111
8      1000
9      1001
A      1010
B      1011
C      1100
D      1101
E      1110
F      1111
Take the hex result that comes from the binary keyword and decode it using the lookup table, stacking your result with the least-significant bit on the right (backwards).

(Thanks to David Cressey for help with this problem.)

DevX Pro

 Submit a Tip Browse "Database Development" Tips Browse All Tips
Comment and Contribute

(Maximum characters: 1200). You have 1200 characters left.

Thanks for your registration, follow us on our social networks to keep up-to-date