如何在不首先将其转换为 int 的情况下将 char 转换为 long?

How to convert a char to a long without first making it an int?

char, int 和 long 都是整数,但有其他 large 位。

我知道如果你从一个整数创建一个 long,例如:

int a=39; long b=a;

long中不是64位的数字,也是32位的整数

当我们制作时:

int a=39; long b=aL;

我读到如果你在 long 上加上一个 L,那么 long 也是一个 64 位的数字。但我读到 Java 在内部将之前的整数视为整数,然后通过 L 将数字变为 64 位。但在此之前,该数字也存储在很短的时间内,长达32位。

所以我读到,通常总是首先在 long 中形成一个 32 位的整数,然后将其变为 64 位。所以即使有人做了 long test =93L;,在 long first 中创建了一个 32 位的整数,然后用 L 扩展它,从而变成 64 位。所以作为一个中间步骤,你总是有一个整数。对吗?

如果是,我怎样才能将一个字符(例如 char test1 ='A' 转换为一个长整数而不先将它们转换为 32 位整数?因为如果我是对的,如果我让 long test2=test1; 没有 long/integer 有 64 位的 long,只有一个有 32 位。是真的吗?

或者现在long里面是一个64位的整数?如果是的话,它之前是 32 位吗?

如果我说的是真的,我怎样才能将一个 char 直接变成 64 位,而不是先把它变成一个 int 呢?

Long 为 64 位。

当您将 int 值分配给 long 变量时,该值将转换为 long。

        long a = 5;  // same as long a = (long) 5;
        long b = 5L;

让我们用一个测试程序试试

public class Test {
    public static void main(String args[]) {
        long a = 'a';
    }
}

编译一下

javac Test.java

我们拆解一下

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

  public static void main(java.lang.String[]);
    Code:
       0: ldc2_w        #2                  // long 97l
       3: lstore_1
       4: return
}

看到这个:

0: ldc2_w        #2                  // long 97l

直接加载97('a'的数值)作为long。没有中间步骤,您的值是 32 位宽。

如果你不直接这样做,当然会得到不同的结果,即数字首先存储为 32 位 int,然后加载到 long(但你明确要求通过将 a 声明为 char,所以这并不奇怪)

public class Test {
    public static void main(String args[]) {
        char a = 'a';
        long b = a;
    }
}

让我们反编译这个

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

  public static void main(java.lang.String[]);
    Code:
       0: bipush        97
       2: istore_1
       3: iload_1
       4: i2l
       5: lstore_2
       6: return
}