比较字节值? [英] Compare byte values?

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

问题描述

我很想知道为什么,当我比较一个 byte 数组和一个值...

I'm curious to know why, when I compare a byte array with a value...

boolean match = ((data[0] & 0xFF) == 0xFE);

...返回 true ..

boolean match = (data[0] == 0xFE);

...不是? 数据是一个 byte 数组,包含

...does not? data is a byte array with

data[0] = (byte) 0xFE;


推荐答案

boolean match = ((data[0] & 0xFF) == 0xFE);

比较整数,因为0xFF是整数,此表达式会扩展您的字节 data [0] 到一个int,并比较括号内的内容到第二个int 0xFE 254 )。因为你说 data [0] (byte)0xFE ,它将首先被缩放为整数 0xFE 并与整数 0xFE 进行比较,因此这是有效的。

compares integers as 0xFF is an integer, this expression will scale up your byte data[0] to an int and compare what's inside the parenthesis to a second int 0xFE (254). As you say data[0] is (byte)0xFE, it will first be scaled to the integer 0xFE and compared to the integer 0xFE, so this works.

boolean match (data[0] == 0xFE);

将一个字节与int 0xFE 254

compares a byte to the int 0xFE : 254

data[0] = (byte) 0xFE; 

是一个字节(因此 signed ),其值为 -2

is a byte (so it's signed) and its value is -2.

-2 不等于 254 ,因此这就是为什么必须将数据[0]字节或者在比较整数 0xFE 之前将其缩放到整数。

-2 is not equal to 254, so that's why you must compare data[0] as a byte or as scale it up to an integer before comparing it the integer 0xFE.

更简单的比较可以是

boolean match = (data[0] == (byte)0xFE);

这篇关于比较字节值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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