C#: int 与 byte[] 互转

        public static int ToInt32(params byte[] v) {
            var r = 0;
            var len = v.Length;
            if (len > 4) {
                len = 4;
            }
            for (var i = 0; i < len; i++) {
                r |= v[i] << 8 * (len - i - 1);
            }
            return r;
        }

        public static byte[] ToBytes(int v) {
            var len = 0;
            for (var i = 0; i < 4; i++) {
                if (v >> 8 * i < 255) {
                    len = i + 1;
                    break;                    
                }
            }
            var bs = new byte[len];
            for (var j = 0; j < bs.Length; j++) {
                bs[j] = (byte)(v >> (bs.Length - j - 1) * 8);
            }
            return bs;
        }

 

posted @ 2017-02-22 11:41  大胡子毛绒老头  阅读(1222)  评论(0编辑  收藏  举报