gpt4 book ai didi

java - 比较 int 和 Java 中的字符常量

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:10:22 25 4
gpt4 key购买 nike

我有一个二进制文件,它使用 4 个字符的集合来形成具有“意义”的整数。例如4字节的'0005',整数形式为808464437。

我宁愿在我的 Java 代码中将它们表示为 '0005' 而不是 808464437。我也不想设置像 final int V0005 = 808464437 这样的常量.

在 C++ 中,我可以执行以下操作:

fileStream->read((byte*) &version, 4); //Get the next bytes and stuff them into the uint32 version

switch (version) {
case '0005':
//do something
case '0006':
//do something
case '0007':
//do something
}

在 Java 中,我的问题不是读取 4 个字节并将它们放入某种数据类型。我的问题是将某些数据类型与 const char 数组 '0005' 进行比较。

如何将 int 或其他形式与 Java 中的 '0005' 等常量字符数组进行比较? 我需要尽可能高效地执行此操作!

最佳答案

感谢您解释您的回答。

以下是将 4 字节转换为 int 的方法,然后您可以将其与所讨论的 int 进行比较:

    int v0005 = ByteBuffer.wrap("0005".getBytes()).asIntBuffer().get();

不幸的是,这是我能看到的唯一方法...可能没有您想要的那么高效,但也许这就是您所需要的。

我建议在您的某个类中将其中一些设置为“常量”,如下所示:

public static final int V0005 = ByteBuffer.wrap("0005".getBytes()).asIntBuffer().get();
public static final int V0006 = ByteBuffer.wrap("0006".getBytes()).asIntBuffer().get();
public static final int V0007 = ByteBuffer.wrap("0007".getBytes()).asIntBuffer().get();
public static final int V0008 = ByteBuffer.wrap("0008".getBytes()).asIntBuffer().get();

然后打开 V0005 等,因为打开原始类型 (int) 是高效的。

关于java - 比较 int 和 Java 中的字符常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15031914/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com