Java打印四个字节的十六进制数字 [英] Java print four byte hexadecimal number

查看:1552
本文介绍了Java打印四个字节的十六进制数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小问题。我有像5421,-1和1这样的数字。我需要以四个字节打印它们,如:
$ b $ pre $ 54 $> 5421 - > 0x0000152D
-1 - > 0xFFFFFFFF
1 - > 0x00000001

另外,我有像浮点数1.2,58.654:

  8.25f  - > 0x41040000 
8.26 - > 0x410428f6
0.7 - > 0x3f333333

我需要将这两种类型的数字转换为十六进制版本,但它们必须正好是四个字节(四对十六进制数字)。

有人知道在Java中怎么可能?请帮忙。

解决方案

这里有两个函数,一个用于整数,一个用于浮点数。

  public static String hex(int n){
//如果需要,调用toUpperCase()
返回String.format(0x%8s,Integer .toHexString(n))。replace('','0');


public static String hex(float f){
//将浮点数更改为原始整数位(根据OP的要求)
return hex(Float .floatToRawIntBits(F));
}


I have a small problem. I have numbers like 5421, -1 and 1. I need to print them in four bytes, like:

5421 -> 0x0000152D
-1   -> 0xFFFFFFFF
1    -> 0x00000001

Also, I have floating point numbers like 1.2, 58.654:

8.25f -> 0x41040000
8.26  -> 0x410428f6
0.7   -> 0x3f333333

I need convert both types of numbers into their hexadecimal version, but they must be exactly four bytes long (four pairs of hexadecimal digits).

Does anybody know how is this possible in Java? Please help.

解决方案

Here are two functions, one for integer, one for float.

public static String hex(int n) {
    // call toUpperCase() if that's required
    return String.format("0x%8s", Integer.toHexString(n)).replace(' ', '0');
}

public static String hex(float f) {
    // change the float to raw integer bits(according to the OP's requirement)
    return hex(Float.floatToRawIntBits(f));
}

这篇关于Java打印四个字节的十六进制数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆