繁体   English   中英

C# 将 long 转换为字节给出错误:& 不能应用于 long 和 ulong

[英]C# Convert long to bytes gives error: & cannot be applied to long and ulong

我想以 100% 的可靠性将 C# 中的 long 转换为 8 字节。

public static byte[] ToBytes(this long thisLong)
    {
        byte[] bytes = new byte[8];
        bytes[0] = (byte)(thisLong & 0xFF);
        bytes[1] = (byte)((thisLong & 0xFF00) >> 8);
        bytes[2] = (byte)((thisLong & 0xFF0000) >> 16);
        bytes[3] = (byte)((thisLong & 0xFF000000) >> 24);
        bytes[4] = (byte)((thisLong & 0xFF00000000) >> 32);
        bytes[5] = (byte)((thisLong & 0xFF0000000000) >> 40);
        bytes[6] = (byte)((thisLong & 0xFF000000000000) >> 48);
        bytes[7] = (byte)((thisLong & 0xFF00000000000000) >> 56);
        return bytes;
    }

但我在“thisLong & 0xFF00000000000000”的最后一行收到错误:

CS0019: Operator '&' cannot be applied to operands of type 'long' and 'ulong' (CS0019)

它适用于 int,所以不会持续很长时间?:

public static byte[] ToBytes(this int thisInt)
    {
        byte[] bytes = new byte[4];
        bytes[0] = (byte)(thisInt & 0xFF);
        bytes[1] = (byte)((thisInt & 0xFF00) >> 8);
        bytes[2] = (byte)((thisInt & 0xFF0000) >> 16);
        bytes[3] = (byte)((thisInt & 0xFF000000) >> 24);
        return bytes;
    }

我不想使用 BitConvertor 来避免字节序问题。

我不想使用 ulong 因为转换可能会失败。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM