一次将Byte数组转换为Integer 2字节 [英] Convert Byte array to Integer 2 bytes at a time

查看:573
本文介绍了一次将Byte数组转换为Integer 2字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字节数组,看起来像

01 00 02 00 73 45 69 A5

所以我必须读取前2个字节并将其转换为整数以获取其值.
接下来的2个字节相同,然后接下来的4个字节相同.

在这里,前2个字节(01 00)的值为1,后2个字节(02 00)的值为2.

I have a byte array which looks something like

01 00 02 00 73 45 69 A5

So i have to read first 2 bytes and convert it into integer to get its value.
Same for next 2 bytes and then next 4 bytes.

Here the value for first 2 bytes (01 00) is 1, next 2 bytes (02 00) is 2.

So could some one help me on this.

推荐答案

该框架有一个类,用于将字节数组转换为原始类型,反之亦然.

System.BitConverter [
The framework has a class to convert byte array to primitive types and vice versa.

The System.BitConverter[^] class is worth a passing glance as it''s very useful and the ToInt16 method is the solution to your problem.

Alan.


我假定无符号数字.

byte [] b

int i = b [x] + b [x + 1] * 256

围绕它抛出一个带有x的2增量的循环.

欢呼
I assume unsigned numbers.

byte[] b

int i = b[x] + b[x + 1] * 256

Throw a loop with an increment of 2 of x around it.

Cheers


无论如何,将两个字节转换为整数非常容易.将第一个字节(作为整数)乘以256,然后加上第二个字​​节.
Anyway, converting two bytes to an integer is very easy. Take the first byte (as an integer), multiply it by 256 and add the second byte.


这篇关于一次将Byte数组转换为Integer 2字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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