SQL Server Get first byte on an Integer

uhry853o  于 12个月前  发布在  其他
关注(0)|答案(3)|浏览(87)

How can I get the first byte of an integer value in SQL Server?

In C#, I can do it easily using the BitConverter :

int x = 383;
var firstByte = BitConverter.GetBytes(x)[0];
Console.WriteLine(x);

// Expected Result: 127

How can I get same value in SQL Server query?

Thanks in advance

gz5pxeao

gz5pxeao1#

Ok, I got alternate help from ChatGPT.

DECLARE @num INT;
SET @num = 383;
SELECT @num & 0xFF AS FirstByte; -- Expected result is 127

But I dont know the theory behind the query.

20jt8wwn

20jt8wwn2#

If you want the first byte, you can run it through a data type cast. Like so:

declare @i int = 383;
select cast(@i as binary(1));

If you need to have that as 127 (which in SQL is some sort of numeric data type), cast the result of the binary cast to tinyint (or whatever you want).

cbjzeqam

cbjzeqam3#

declare @i int = 383;
select cast(cast(@i as binary(1)) as int);

相关问题