C# 基本数据类型和Byte [] 相互转换

本文提供了C#中基本数据类型如Int32、Int16与Byte数组间相互转换的方法实现,包括具体代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

        public static byte[] Int32ToBytes(int intValue)
        {
            byte[] bytes = new byte[4];
            bytes[0] = (byte)(intValue & 0x000000FF);
            bytes[1] = (byte)((intValue & 0x0000FF00) >> 8);
            bytes[2] = (byte)((intValue & 0x00FF0000) >> 16);
            bytes[3] = (byte)((intValue & 0xFF000000) >> 24);
            return bytes;
        }

        public static int BytesToInt32(byte[] bytes)
        {
            long longValue = (uint)bytes[0] & 0x000000FF
                | ((uint)bytes[1] << 8) & 0x0000FF00
                | ((uint)bytes[2] << 16) & 0x00FF0000
                | ((uint)bytes[3] << 24) & 0xFF000000;
            return (int)longValue;
        }

        public static byte[] Int16ToBytes(short shortValue)
        {
            byte[] bytes = new byte[2];
            bytes[0] = (byte)(shortValue & 0x000FF);
            bytes[1] = (byte)((shortValue & 0xFF00) >> 8);
            return bytes;
        }


        public static short BytesToInt16(byte[] bytes)
        {
            short longValue = (short)((uint)bytes[0] & 0x00FF
                            | ((uint)bytes[1] << 8) & 0xFF00);
            return longValue;
        }


posted on 2012-06-13 08:34 小小程序员001 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/musicfans/archive/2012/06/13/2819315.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值