在Java中没有if语句转换布尔值,整型 [英] Converting Boolean to Integer in Java without If-Statements

查看:375
本文介绍了在Java中没有if语句转换布尔值,整型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道是否有一个布尔值,一个int转换,而无需使用if语句(如不打破管道)的方式。例如,我可以写

I'm wondering if there's a way to convert a boolean to an int without using if statements (as not to break the pipeline). For example, I could write

int boolToInt( boolean b ){
  if ( b )
    return 1
  return 0

但我不知道是否有办法做到这一点没有if语句,如Python的

But I'm wondering if there's a way to do it without the if statement, like Python's

bool = True 
num = 1 * ( bool )

我也弄清楚你可以做

I also figure you could do

boolean bool = True;
int myint = Boolean.valueOf( bool ).compareTo( false );

这将创建一个额外的对象,虽然如此,这真是浪费了,我发现它比if语句的方式更慢(这并不一定是低效的,只是有一个弱点)。

This creates an extra object, though, so it's really wasteful and I found it to be even slower than the if-statement way (which isn't necessarily inefficient, just has the one weakness).

推荐答案

您不能使用布尔以外的如果。然而,这并不意味着将有在汇编级分支。

You can't use a boolean other than in a if. However it does not mean that there will be a branch at the assembly level.

如果您检查方法的编译code(顺便说一下,使用回复B 1:0; 编译完全相同的指令?),你会看到,它不使用跳:

If you check the compiled code of that method (by the way, using return b ? 1 : 0; compiles to the exact same instructions), you will see that it does not use a jump:

0x0000000002672580: sub    $0x18,%rsp
0x0000000002672587: mov    %rbp,0x10(%rsp)    ;*synchronization entry
0x000000000267258c: mov    %edx,%eax
0x000000000267258e: add    $0x10,%rsp
0x0000000002672592: pop    %rbp
0x0000000002672593: test   %eax,-0x2542599(%rip)        # 0x0000000000130000
                                                ;   {poll_return}
0x00000000025b2599: retq  

请注意:这是热点服务器7 - 你可能会在不同的虚拟机得到不同的结果。

Note: this is on hotspot server 7 - you might get different results on a different VM.

这篇关于在Java中没有if语句转换布尔值,整型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆