سؤال

Using SQL Server 2008.

Let's say I have 3 numbers to store.

  • First number is any 6bit number
  • Second is any 4bit
  • Third is also any 6bit number

For example:

declare @firstNumber_6bit  tinyint = 50
declare @secondNumber_4bit tinyint = 7
declare @thirdNumber_6bit  tinyint = 63

I need to store those 3 numbers in a 2 byte binary (16bit) variable. So, the binary values for the example are:

  • 50 is 110010,
  • 7 is 0111
  • 63 is 111111
  • The 2 bytes to store are 11001001 11111111

So either one of the following lines should store those values:

declare @my3NumbersIn2Bytes binary(2) = 51711

or

declare @my3NumbersIn2Bytes binary(2) = 0xC9FF

(sorry if I'm messing the byte order in big / little endian, but that's not the point).

Storing and retriving those numbers is a trivial task with .net CLR, but I'm trying to solve this in pure T-SQL and as we know there is no bit shifting in SQL Server. I saw a lot of examples out there that use memory tables to solve problems like these, but that seems totally overkill for doing a simple bit shift... I was thinking something more like a substring for bits could do the trick. I just want to be sure there's no other way to solve this before going the overkill way.

So my question is, what is the most effective way to store those 3 numbers and recover them?

Thanks.-

هل كانت مفيدة؟

المحلول

declare @firstNumber_6bit  tinyint = 50
declare @secondNumber_4bit tinyint = 7
declare @thirdNumber_6bit  tinyint = 63

declare @my3NumbersIn2Bytes binary(2)

select @my3NumbersIn2Bytes = @firstNumber_6bit*1024 + @secondNumber_4bit *64 + @thirdNumber_6bit
--extract values
select @firstNumber_6bit = @my3NumbersIn2Bytes/1024
select @secondNumber_4bit = (@my3NumbersIn2Bytes%1024)/64
select @thirdNumber_6bit = (@my3NumbersIn2Bytes%1024)%64

select convert(varchar(max), @my3NumbersIn2Bytes, 1) -- just for display
, @firstNumber_6bit
, @secondNumber_4bit
, @thirdNumber_6bit

SQL Fiddle Demo

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top