如何在java中将11111111表示为一个字节 [英] How to represent 11111111 as a byte in java

查看:59
本文介绍了如何在java中将11111111表示为一个字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我说 0b11111111 是 java 中的一个字节时,它说不能将 int 转换为字节",这是因为,据我所知,11111111=256,并且 java 中的字节是有符号的,从 -128 到127. 但是,如果一个字节只是 8 位数据,那么 11111111 不是 8 位吗?我知道 11111111 可能是一个整数,但在我的情况下,它必须表示为一个字节,因为它必须以字节形式发送到文件.那么我如何将一个包含 11111111 位的字节发送到一个文件(顺便说一下,这是我的问题)?当我尝试打印 -1 的二进制值时,我得到 111111111111111111111111111111111,这是为什么?我真的不明白签名字节是如何工作的.

When I say that 0b11111111 is a byte in java, it says " cannot convert int to byte," which is because, as i understand it, 11111111=256, and bytes in java are signed, and go from -128 to 127. But, if a byte is just 8 bits of data, isn't 11111111 8 bits? I know 11111111 could be an integer, but in my situation it must be represented as a byte because it must be sent to a file in byte form. So how do I send a byte with the bits 11111111 to a file(by the way, this is my question)? When I try printing the binary value of -1, i get 11111111111111111111111111111111, why is that? I don't really understand how signed bytes work.

推荐答案

您需要将值转换为一个字节:

You need to cast the value to a byte:

byte b = (byte) 0b11111111;

您需要转换的原因是 0b11111111 是一个 int 文字(十进制值为 255)并且它超出了有效的 byte 值(-128 到 +127).

The reason you need the cast is that 0b11111111 is an int literal (with a decimal value of 255) and it's outside the range of valid byte values (-128 to +127).

这篇关于如何在java中将11111111表示为一个字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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