将一个 []byte 数组(Java 双重编码)转换为 Float64。

huangapple go评论64阅读模式
英文:

Converting a []byte array (java double encoded) to Float64

问题

所以,我正在尝试将一个字节数组解码为Float64。我尝试了很多不同的方法,都是在StackOverflow上找到的,但是到目前为止都没有成功!这是我尝试的Go Playground链接。预期值应该是3177408.5。原始值是一个Java double,编码为IEEE 754浮点数。

编辑:

该值是使用org.apache.hadoop.hbase.util.Bytes.toBytes方法进行编码的。

double v = 3445713.95;
long ff;

ff = Double.doubleToRawLongBits(v);

bArr = toBytes(ff)

public static byte[] toBytes(long val) {
    byte[] b = new byte[8];

    for(int i = 7; i > 0; --i) {
        b[i] = (byte)((int)val);
        val >>>= 8;
    }

    b[0] = (byte)((int)val);
    return b;
}

实际上应该是:3445713.95

编辑2:

我的错误是没有仔细思考就直接粘贴了我得到的代码,Java并不是我擅长的。事实证明,在整个流程中(多个系统之间的通信)存在问题,导致值被破坏。我将把@Ainar-G的解决方案标记为正确,因为它实际上返回了接近预期值的结果。

英文:

So, I'm trying to decode a byte array to Float64. I've tried a bunch of different ways, found all over StackOverflow, but no luck so far! Here's the go playground link to what I have tried.
The expected value should be 3177408.5. The original value is a Java double, encoded as IEEE 754 floating-point

Edit:

The value is encoded using the org.apache.hadoop.hbase.util.Bytes.toBytes method.

double v = 3445713.95;
long ff;

ff = Double.doubleToRawLongBits(v);

bArr = toBytes(ff)

public static byte[] toBytes(long val) {
    byte[] b = new byte[8];

    for(int i = 7; i > 0; --i) {
        b[i] = (byte)((int)val);
        val >>>= 8;
    }

    b[0] = (byte)((int)val);
    return b;
}

And actually should be: 3445713.95

Edit2:

My bad for actually just pasting code I was given, without thinking much first, Java is not exactly my cup of tea. Turns out there is a problem somewhere along the pipeline (multiple systems communicating), and value is getting corrupted. I'll mark @Ainar-G's solution as correct, since it actually gives back something close to the expected.

答案1

得分: 2

我能找到的最接近的方法是使用binary.BigEndian.Uint64

b := []byte("AJ\x02\xef\xe1\xaf(l")
u := binary.BigEndian.Uint64(b)
f := math.Float64frombits(u)
fmt.Printf("%f", f)

这将给出结果3409375.763158。请确保在Java端正确编码你的浮点数。

Playground: https://play.golang.org/p/4KGZoWjLTF.

英文:

The closest I can get is if I use binary.BigEndian.Uint64:

b := []byte("AJ\x02\xef\xe1\xaf(l")
u := binary.BigEndian.Uint64(b)
f := math.Float64frombits(u)
fmt.Printf("%f", f)

This gives me 3409375.763158. Make sure you're encoding your float correctly on the Java side.

Playground: https://play.golang.org/p/4KGZoWjLTF.

huangapple
  • 本文由 发表于 2016年11月30日 22:12:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/40890557.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定