3转换成字节有符号整数在C# [英] Converting 3 bytes into signed integer in C#
问题描述
我想3个字节转换为C#符号整数(大端)。
I'm trying to convert 3 bytes to signed integer (Big-endian) in C#.
我试图用 BitConverter .ToInt32
方法,但我的问题是什么样的价值应该有拉特字节。
I've tried to use BitConverter.ToInt32
method, but my problem is what value should have the lats byte.
任何人都可以建议我,我怎么能做到这一点的方式不同?
Can anybody suggest me how can I do it in different way?
我还需要转换5(或6或7)个字节来签订长,是没有任何一般规则该怎么办呢?
I also need to convert 5 (or 6 or 7) bytes to signed long, is there any general rule how to do it?
感谢您事先的任何帮助。
Thanks in advance for any help.
推荐答案
作为最后的手段,你可以随时切换+添加自己:
As a last resort you could always shift+add yourself:
byte b1, b2, b3;
int r = b1 << 16 + b2 << 8 + b3;
只要将B1 / B2 / B3,直到你想要的结果。
Just swap b1/b2/b3 until you have the desired result.
在第二个想法,这绝不会产生负值。结果
你想要什么结果当MSB> = 0x80的?
On second thought, this will never produce negative values.
What result do you want when the msb >= 0x80 ?
2部分,蛮力符号扩展:
Part 2, brute force sign extension:
private static int Bytes2Int(byte b1, byte b2, byte b3)
{
int r = 0;
byte b0 = 0xff;
if ((b1 & 0x80) != 0) r |= b0 << 24;
r |= b1 << 16;
r |= b2 << 8;
r |= b3;
return r;
}
我已经测试这b $ b
I've tested this with:
byte[] bytes = BitConverter.GetBytes(p);
int r = Bytes2Int(bytes[2], bytes[1], bytes[0]);
Console.WriteLine("{0} == {1}", p, r);
几 P
。
这篇关于3转换成字节有符号整数在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!