无符号 byte java_我们能用Java做无符号字节吗?

原语是用Java签名的,这与它们在内存/传输中的表示方式无关-字节仅为8位,是否将其解释为有符号范围取决于您。没有魔法标志可以说“这是签名的”或“这是未签名的”。

在对原语进行签名时,Java编译器将阻止您将大于+127的值分配给一个字节(或低于-128)。但是,没有什么可以阻止您为了实现这一点而降低int(或Short):int i = 200; // 0000 0000 0000 0000 0000 0000 1100 1000 (200)byte b = (byte) 200;

// 1100 1000 (-56 by Java specification, 200 by convention)/*

* Will print a negative int -56 because upcasting byte to int does

* so called "sign extension" which yields those bits:

* 1111 1111 1111 1111 1111 1111 1100 1000 (-56)

*

* But you could still choose to interpret this as +200.

*/System.out.println(b); // "-56"/*

* Will print a positive int 200 because bitwise AND with 0xFF will

* zero all the 24 most significant bits that:

* a) were added during upcasting to int which took place silently

*    just before evaluating the bitwise AND operator.

*    So the `b & 0xFF` is equivalent with `((int) b) & 0xFF`.

* b) were set to 1s because of "sign extension" during the upcasting

*

* 1111 1111 1111 1111 1111 1111 1100 1000 (the int)

* &

* 0000 0000 0000 0000 0000 0000 1111 1111 (the 0xFF)

* =======================================

* 0000 0000 0000 0000 0000 0000 1100 1000 (200)

*/System.out.println(b & 0xFF); // "200"/*

* You would typically do this *within* the method that expected an

* unsigned byte and the advantage is you apply `0xFF` only once

* and than you use the `unsignedByte` variable in all your bitwise

* operations.

*

* You could use any integer type longer than `byte` for the `unsignedByte` variable,

* i.e. `short`, `int`, `long` and even `char`, but during bitwise operations

* it would get casted to `int` anyway.

*/void printUnsignedByte(byte b) {

int unsignedByte = b & 0xFF;

System.out.println(unsignedByte); // "200"}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值