在java中从布尔值转换为字节

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25360375/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 00:12:20  来源:igfitidea点击:

convert from boolean to byte in java

javabooleanbytetype-conversion

提问by Martin

I need to set byte value as method parameter. I have boolean variable isGenerated, that determines the logic to be executed within this method. But I can pass directly boolean as byte parameter this is not allowed and can't be cast in java. So the solution I have now looks like this:

我需要将字节值设置为方法参数。我有布尔变量isGenerated,它确定要在此方法中执行的逻辑。但是我可以直接将布尔值作为字节参数传递,这是不允许的,也不能在 java 中进行转换。所以我现在的解决方案是这样的:

myObj.setIsVisible(isGenerated ? (byte)1 : (byte)0);

But it seems odd for me. Maybe some better solution exists to do this?

但对我来说似乎很奇怪。也许存在一些更好的解决方案来做到这一点?

采纳答案by PrR3

your solution is correct.

你的解决方案是正确的。

if you like you may avoid one cast by doing it the following way:

如果您愿意,可以通过以下方式避免一次演员表:

myObj.setIsVisible((byte) (isGenerated ? 1 : 0 ));

additionally you should consider one of the following changes to your implementation:

此外,您应该考虑对您的实现进行以下更改之一:

  • change your method to something like setVisiblityState(byte state)if you need to consider more than 2 possible states

  • change your method to setIsVisible(boolean value)if your method does what it's looking like

  • 如果您需要考虑超过 2 种可能的状态,请将您的方法更改为类似setVisiblityState(byte state)的方法

  • 如果您的方法看起来像这样,请将您的方法更改为setIsVisible(boolean value)

回答by AlexR

It is not odd. It is OK. The odd is that you need to transform typed boolean value to not self explainable byte. However sometimes we have to do this when working with legacy APIs.

这并不奇怪。没关系。奇怪的是,您需要将类型化的布尔值转换为不可自我解释的字节。然而,有时我们在使用遗留 API 时必须这样做。

BTW if you want to save memory you can use 1 bit instead of byte, so you can group several boolean flags together while using bit for each boolean value. But this technique is relevant for huge amounts of data only when saving several bytes can be significant.

顺便说一句,如果您想节省内存,您可以使用 1 位而不是字节,因此您可以将几个布尔标志组合在一起,同时为每个布尔值使用位。但是,只有当节省几个字节可能很重要时,这种技术才与大量数据相关。

回答by Federico Traiman

You can use this solution. I found it on thisvery useful page

您可以使用此解决方案。我在这个非常有用的页面上找到了它

boolean vIn = true;
byte vOut = (byte)(vIn?1:0);