C#INT为byte [] [英] C# int to byte[]

查看:190
本文介绍了C#INT为byte []的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我需要转换的 INT 字节[] 所以我可以使用 BitConverter.GetBytes()。但如果我应遵循这样的:

If I need to convert an int to a byte[] so I could use BitConverter.GetBytes(). But if I should follow this:

有符号整数的XDR是一个32位数据的连接codeS中的一个整数      范围[-2147483648,2147483647]。该整数再presented在      二进制补码。最多和最少的显著字节      0和3,分别整数声明如下:

An XDR signed integer is a 32-bit datum that encodes an integer in the range [-2147483648,2147483647]. The integer is represented in two's complement notation. The most and least significant bytes are 0 and 3, respectively. Integers are declared as follows:

来源:RFC1014 3.2

Source: RFC1014 3.2

用什么方法,我应该用那么有没有办法做到这一点?它如何看,如果你写你自己的呢?

What method should I use then if there is no method to do this? How would it look like if you write your own?

我不明白的文字100%,所以我不能在我自己实现它。

I don't understand the text 100% so I can't implement it on my own.

推荐答案

该RFC只是想说,有符号整数是一个正常的4字节的整数,下令在大端方式字节。

The RFC is just trying to say that a signed integer is a normal 4-byte integer with bytes ordered in a big-endian way.

现在,你是最有可能工作一小端机器上 BitConverter.GetBytes()会给你的字节[] 逆转。所以,你可以尝试:

Now, you are most probably working on a little-endian machine and BitConverter.GetBytes() will give you the byte[] reversed. So you could try:

int intValue;
byte[] intBytes = BitConverter.GetBytes(intValue);
Array.Reverse(intBytes);
byte[] result = intBytes;

对于code是最轻便的,但是,你可以做到这一点是这样的:

For the code to be most portable, however, you can do it like this:

int intValue;
byte[] intBytes = BitConverter.GetBytes(intValue);
if (BitConverter.IsLittleEndian)
    Array.Reverse(intBytes);
byte[] result = intBytes;

这篇关于C#INT为byte []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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