将两个字节读取为整数? [英] Read two bytes into an integer?

查看:59
本文介绍了将两个字节读取为整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从文件中读取的 byte [] ,我想从其中的两个字节中获取一个 int .这是一个示例:

I have a byte[] that I've read from a file, and I want to get an int from two bytes in it. Here's an example:

byte[] bytes = new byte[] {(byte)0x00, (byte)0x2F, (byte)0x01, (byte)0x10, (byte)0x6F};
int value = bytes.getInt(2,4); //This method doesn't exist

这应使 value 等于 0x0110 或十进制 272 .但是显然, byte [].getInt()不存在.我该如何完成这项任务?

This should make value equal to 0x0110, or 272 in decimal. But obviously, byte[].getInt() doesn't exist. How can I accomplish this task?

上面的数组只是一个例子.实际值我不知道.

The above array is just an example. Actual values are unknown to me.

推荐答案

您应该选择简单的方法:

You should just opt for the simple:

int val = ((bytes[2] & 0xff) << 8) | (bytes[3] & 0xff);

您甚至可以编写自己的辅助函数 getBytesAsWord(byte []个字节,int开头)以为您提供该功能,如果您不希望计算增加代码量,但是我认为那可能太过分了.

You could even write your own helper function getBytesAsWord (byte[] bytes, int start) to give you the functionality if you didn't want the calculations peppering your code but I think that would probably be overkill.

这篇关于将两个字节读取为整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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