Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

three boolean variables convert into string

Status
Not open for further replies.

navrsalemile

Programmer
Feb 6, 2005
62
CA
Hi all,

I have three boolean variables:

boolean flag1;
boolean flag2;
boolean flag3;

I want to represent them as octal number and convert this octal number into integer represented as String, i.e. if flags are:

flag1 is true
flag2 is false
flag3 is true

then String should be "5" which is binary 5 (0b101).

I came up with:
String suffix = Integer.toString((int)(flag1 ? 1 : 0) << 2 | (int)(flag2 ? 1 : 0) << 1 | (int)(flag3 ? 1 : 0));

but wonder if there is shorter more elegant solution?
many thanks,
mile
 
Er, what's octal got to do with it? Octal is Base 8.

From your post, it looks like you want to interpret a collection of booleans as a binary value and calculate the corresponding integer value represented as a String.

Off the top of my head, I can't think of a shorter solution than yours.

Tim
---------------------------
"Your morbid fear of losing,
destroys the lives you're using." - Ozzy
 
If you really want if octal:

[/code]

String suffix = Integer.toString((flag1 ? 1 : 0) +(flag2 ? 2 : 0) + (flag3 ? 4 : 0));

Code:
It isn't more ellegant, but shorter and possibly faster (didn't test it).

Cheers,

Dian
 
But anyway, a three digit binary number has a decimal range of 0 to 7, which is identical to its Octal representation since it never reaches 8 (10 in octal).

Tim
---------------------------
"Your morbid fear of losing,
destroys the lives you're using." - Ozzy
 
That's true.

If not, he'd need yo use the Integer.toString(num,8).

Cheers,

Dian
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top