转换的Java方法C#:在转换字节整数与位移位运算符 [英] Converting java method to C#: converting bytes to integers with bit shift operators

查看:231
本文介绍了转换的Java方法C#:在转换字节整数与位移位运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以下2种方法到C#转换,而不.NET编译器在我抱怨。坦率地说我只是不明白怎么这两种方法是真正在幕后工作。所以,答案和解释,将是巨大的在这里。

I am trying to convert the following 2 methods into c# without the .net compiler complaining at me. Quite frankly I just don't understand how the two methods are really working behind the scenes. So an answer and explanation would be great here.

public static int bytesToInt(byte b0, byte b1, byte b2, byte b3)
{
        return (((int)b0 << 24) & 0xFF000000)
            | (((int)b1 << 16) & 0x00FF0000)
            | (((int)b2 << 8) & 0x0000FF00)
            | ((int)b3 & 0x000000FF);
}

public static byte[] charToBytes(char c)
{
    byte[] result = new byte[2];

    result[0] = (byte) ((c >>> 8) & 0x00FF);
    result[1] = (byte) ((c >>> 0) & 0x00FF);

    return result;
}

的第二种方法是因为所使用的移位操作符是不同的特别混乱与第一方法

The second method is particularly confusing because of the shift operator being used that is different that the first method.

感谢您事先的任何帮助。

Thanks in advance for any help.

推荐答案

在>>>是无符号右移在Java中运营商。它可以与>>,然而,注册延伸的值如果是负值来代替。在这种情况下,然而,使用>>算子是无害的,因为结果是减少至一个字节中的值(&放大器;设为0x00FF )。

The ">>>" is the unsigned right shift operator in Java. It can be replaced with ">>", which, however, sign-extends the value if it's negative. In this case, however, the use of the ">>" operator is harmless, since the result is reduced to a single byte in value (& 0x00FF).

在bytesToInt使用的掩蔽(&放大器; 0xFF000000 等)为在Java中必要的,因为在Java中,字节符号值,也就是说,它们可以是正的或负面的,转换为 INT 可以登录扩展为负值。在C#,但是,字节只能是正的,所以没有掩蔽是必要的。因此,该bytesToInt方法可以简单地重写为:

The masking used in bytesToInt (& 0xFF000000 and so on) was necessary in Java because in Java, bytes are signed values, that is, they can be positive or negative, and converting to int can sign-extend a negative value. In C#, however, bytes can only be positive, so no masking is necessary. Thus, the bytesToInt method can be rewritten simply as:

return (((int)b0 << 24))    
  | (((int)b1 << 16))
  | (((int)b2 << 8))
  | ((int)b3);

这篇关于转换的Java方法C#:在转换字节整数与位移位运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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