C#将int存储在字节数组中 [英] C# store int in byte array

查看:83
本文介绍了C#将int存储在字节数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个小项目,我需要在字节数组中存储4个 int 类型(稍后将在套接字上发送).

I work on a small project and i need to store 4 int types in a byte array(which will be sent later on a socket).

这是代码:

       int a = 566;          
       int b = 1106;
       int c = 649;
       int d = 299;
        byte[] bytes = new byte[16];

        bytes[0] = (byte)(a >> 24);
        bytes[1] = (byte)(a >> 16);
        bytes[2] = (byte)(a >> 8);
        bytes[3] = (byte)a;

我将第一个值的位移位了,但是现在不确定如何将其取回...执行相反的过程.

I shifted the bits of the first value,but i'm not sure now how to retrieve it back...doing the reversed process.

我希望我的问题很清楚,如果我错过了什么,我将很高兴再次解释.谢谢.

I hope my question is clear,if i missed somthing i'll be glad to explain it again. Thanks.

推荐答案

要从字节数组中提取 Int32 ,请使用以下表达式:

To extract the Int32 back out from the byte array, use this expression:

int b = bytes[0] << 24
      | bytes[1] << 16
      | bytes[2] << 8
      | bytes[3]; // << 0

这是一个演示的 .NET小提琴.

这篇关于C#将int存储在字节数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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