我应该如何将浮子转换为未签名的整数?

问题描述 投票:0回答:1
我需要将浮点转换为我正在从事的项目的未签名整数,类似于基本的浮动到Int铸件,但具有未签名的INT作为输出,对于负面的浮子返回零。我知道有一种方法可以将它们转换为

签名的整数,但是我需要nunsigned整数。我不能简单地提高渴望,因为我还需要将双打转换为未签名的渴望。我发现的唯一方法是转换为字符串,然后转换为未签名的int: int i; try { i = Integer.parseUnsignedInt(Float.toString((float)Math.floor(f))); } catch (NumberFormatException e) { i = 0; }

否,对我来说这似乎太拼凑了。我敢肯定,有一种更好的方法可以做到这一点,但是我似乎找不到在线上的任何东西,而chatgpt只是像往常一样胡说八道。有更好的转换方法吗?

Edit:

  • 0.0f
    应该给
    0
  • -1.5f
  • 应该给
    0
    NaN
  • 应该给
  • 0
    1.7f
    应该给
  • 1
  • 3e+9f
    应给予
    -1294967296
  • (有30亿个签名的赞美)。
  • 1e+12f
    应该给
    0
  • 简单
    if
    语句
  • 我正在通过@Anonymous转换评论以及它们链接到此答案的代码。如果您的
float
java floating-point integer
1个回答
0
投票
long

,并且在未签名的
int
范围内,请进一步施放至

int

。否则结果为0。

private static int convertFloatToUnsignedInt(float f) {
    if (f >= 0) {
        long asLong = (long) f;
        // Within range of unsigned int?
        if (asLong < 0x1_0000_0000L) {
            return (int) asLong;
        }
    }
    return 0;
}
llet尝试使用您的示例
float
值:
    float[] exampleFloats = { 0.0f, -0.1f, -1.5f, Float.NaN, 1.7f, 3e+9f, 1e+12f };
    for (float exampleFloat : exampleFloats) {
        int asInt = convertFloatToUnsignedInt(exampleFloat);
        System.out.format(Locale.ENGLISH, "%14.1f -> %10s or %11d%n",
                exampleFloat, Integer.toUnsignedString(asInt), asInt);
    }

输出为
           0.0 ->          0 or           0
          -0.1 ->          0 or           0
          -1.5 ->          0 or           0
           NaN ->          0 or           0
           1.7 ->          1 or           1
  3000000000.0 -> 3000000000 or -1294967296
999999995904.0 ->          0 or           0

输出显示了转换为相同的
float

的值,无符号的值
int
值转换为同一

int

的签名值。
double

未签名

long

…但是双重到长时间呢?

对于使用相同标准转换为未签名的情况,您可以通过
double
转换:

long

也要尝试一下:

BigDecimal

输出:
private static final double MAX_UNSIGNED_LONG_PLUS_ONE
        = 2.0 *(((double) Long.MAX_VALUE) + 1);

private static long convertDoubleToUnsignedLong(double d) {
    if (d >= 0 && d < MAX_UNSIGNED_LONG_PLUS_ONE) {
        return new BigDecimal(d).longValue();
    }
    return 0;
}
两种转换方法不是100%一致的。您可能可以简化它们以获得更一致的代码。
查看代码在线运行

重复链接@anonymous
代码在此处在线运行。在上面,我对其代码进行了较小的调整。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.