Java 后缀分隔符

发布于 2024-12-16 16:28:45 字数 243 浏览 3 评论 0原文

有必要使用后缀分隔符来表示源代码中使用的常量类型,例如 L 表示 long。然而,对于shorts和bytes没有分隔符,所以我需要像这样显式地转换常量值:

short x = (short)0x8000;

我想知道Java是否在编译的字节码中采取额外的步骤来实际将其从整数类型转换为short类型,或者是否这样做知道这将适合一个单词并按原样使用常量吗?否则,有没有办法可以后缀这样的数字来表示短或字节?

It's necessary to use a postfix delimiter to denote the type of constant being used in the source code, like L for long. However, for shorts and bytes there are no delimiters, so I need to explicitly cast the constant value like so:

short x = (short)0x8000;

I was wondering if Java takes extra steps in the compiled bytecode to actually convert this from an integer type to a short, or does it know that this will fit into a word and use the constant as is? Otherwise, is there a way I can postfix numbers like these to denote short or byte?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

雨落□心尘 2024-12-23 16:28:45

我想知道 Java 是否在编译的字节码中采取额外的步骤来实际将其从整数类型转换为短整型,或者它是否知道这将适合一个单词并按原样使用常量?

我认为它知道它适合一个单词并按原样使用它。例如字节码:

public class IntToShortByteCode {
   public static void main(String... args){
        short x = (short)0x8888;
        System.out.println(x);
    }
}

is (javac 1.6.0_14):

Compiled from "IntToShortByteCode.java"
public class IntToShortByteCode extends java.lang.Object{
public IntToShortByteCode();
  Code:
   0:   aload_0
   1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
   4:   return

public static void main(java.lang.String[]);
  Code:
   0:   sipush  -30584
   3:   istore_1
   4:   getstatic       #2; //Field java/lang/System.out:Ljava/io/PrintStream;
   7:   iload_1
   8:   invokevirtual   #3; //Method java/io/PrintStream.println:(I)V
   11:  return

}

否则,有没有办法可以在后缀这样的数字来表示短或字节?

不。

I was wondering if Java takes extra steps in the compiled bytecode to actually convert this from an integer type to a short, or does it know that this will fit into a word and use the constant as is?

I think it knows that it will fit into a word and uses it as is. For instance bytecode for:

public class IntToShortByteCode {
   public static void main(String... args){
        short x = (short)0x8888;
        System.out.println(x);
    }
}

is (javac 1.6.0_14):

Compiled from "IntToShortByteCode.java"
public class IntToShortByteCode extends java.lang.Object{
public IntToShortByteCode();
  Code:
   0:   aload_0
   1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
   4:   return

public static void main(java.lang.String[]);
  Code:
   0:   sipush  -30584
   3:   istore_1
   4:   getstatic       #2; //Field java/lang/System.out:Ljava/io/PrintStream;
   7:   iload_1
   8:   invokevirtual   #3; //Method java/io/PrintStream.println:(I)V
   11:  return

}

Otherwise, is there a way I can postfix numbers like these to denote short or byte?

No.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文