有没有一种很好的方式,为int分成两个短裤(.NET)? [英] Is there a nice way to split an int into two shorts (.NET)?

查看:191
本文介绍了有没有一种很好的方式,为int分成两个短裤(.NET)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为这是不可能的,因为的Int32 有1位符号,并具有数字信息的31位和Int16的有1位符号和数字信息的15位,这导致具有2位标志和信息30位

I think that this is not possible because Int32 has 1 bit sign and have 31 bit of numeric information and Int16 has 1 bit sign and 15 bit of numeric information and this leads to having 2 bit signs and 30 bits of information.

如果这是真的话,我不能有一个的Int32 成两的Int16 。这是真的吗?

If this is true then I cannot have one Int32 into two Int16. Is this true?

在此先感谢。

附加信息:使用Vb.Net,但我认为我可以翻译没有问题的一个C#的答案

EXTRA INFORMATION: Using Vb.Net but I think that I can translate without problems a C# answer.

什么起初我想要做的是将一种 UInt32的两个 UINT16 ,因为这是一个库,互动与WORD的机器。然后我意识到 UINT 不符合CLS,并试图用的Int32 做同样的INT16

What initially I wanted to do was to convert one UInt32 to two UInt16 as this is for a library that interacts with WORD based machines. Then I realized that Uint is not CLS compliant and tried to do the same with Int32 and Int16.

更糟糕的是:执行 A = CTYPE(C和放大器; HFFFF,Int16的); 抛出发生OverflowException 。我希望这句话是一样的 A =(Int16的)(C&安培; 0xFFFF的); (不抛出异常)

EVEN WORSE: Doing a = CType(c And &HFFFF, Int16); throws OverflowException. I expected that statement being the same as a = (Int16)(c & 0xffff); (which does not throw an exception).

推荐答案

这应该工作:

int original = ...;
byte[] bytes = BitConverter.GetBytes(original);
short firstHalf = BitConverter.ToInt16(bytes, 0);
short secondHalf = BitConverter.ToInt16(bytes, 2);

编辑:

通过测试为0x7FFFFFFF,它的工作原理

tested with 0x7FFFFFFF, it works

byte[] recbytes = new byte[4];
recbytes[0] = BitConverter.GetBytes(firstHalf)[0];
recbytes[1] = BitConverter.GetBytes(firstHalf)[1];
recbytes[2] = BitConverter.GetBytes(secondHalf)[0];
recbytes[3] = BitConverter.GetBytes(secondHalf)[1];
int reconstituted = BitConverter.ToInt32(recbytes, 0);

这篇关于有没有一种很好的方式,为int分成两个短裤(.NET)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆