Java simple boolean to byte conversion

I have an array of 8 booleans which I want to simply convert to a byte. Is there a simple way to do this? Or do I have to use for loop?

Personally I'd prefer a simple up to two lines solution if it exists.

Thanks for help.

EDIT: Possible duplicate is just one boolean to a byte, I have an array.

ANOTHER EDIT: I get a byte from a udp packet then I set the first bit (boolean) to false, then I would need to get a byte out of that again.


I think a loop is better, but if you must have a one liner :

byte b = (byte)((bool[0]?1<<7:0) + (bool[1]?1<<6:0) + (bool[2]?1<<5:0) + 
                (bool[3]?1<<4:0) + (bool[4]?1<<3:0) + (bool[5]?1<<2:0) + 
                (bool[6]?1<<1:0) + (bool[7]?1:0));

For the input :

boolean[] bool = new boolean[] {false,false,true,false,true,false,true,false};

you get the byte 42.

Need Your Help

What is “(), the Unit value”?


My scalatest unit test fails with the following message:

Java: Get URI from FilePath

java url uri filepath

I've little knowledge of Java. I need to construct a string representation of an URI from FilePath(String) on windows. Sometimes the inputFilePath I get is: file:/C:/a.txt and sometimes it is: C:/a...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.