convert from boolean to byte in java

前端 未结 3 1096
旧巷少年郎
旧巷少年郎 2021-02-18 21:26

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 direc

相关标签:
3条回答
  • 2021-02-18 21:50

    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.

    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.

    0 讨论(0)
  • 2021-02-18 21:56

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

    boolean vIn = true;
    byte vOut = (byte)(vIn?1:0);
    
    0 讨论(0)
  • 2021-02-18 22:03

    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

    0 讨论(0)
提交回复
热议问题