Java的:二进制字符串转换为十六进制字符串 [英] Java: convert binary string to hex string

查看:3813
本文介绍了Java的:二进制字符串转换为十六进制字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要二进制字符串转换为十六进制字符串,但我有一个问题。
我用这种方法转换的二进制字符串为十六进制字符串:

I need to convert the binary string to a hex string but i have a problem. I converted the binary string to a hex string by this method:

public static String binaryToHex(String bin){
   return Long.toHexString(Long.parseLong(bin,2));
}

这是确定!但我失去了零字符串的左边。
例如:

it's ok! but I lose the zeros to the left of the string. Ex:

该方法返回此:123456789ABCDEF,
但我想返回此:

the method return this: 123456789ABCDEF, but i want returned this:

00000123456789ABCDEF

00000123456789ABCDEF

推荐答案

而不是 Long.toHexString 我会使用的Long.parseLong 解析值,然后的String.format 来输出(在您的示例21)与所需的宽度值:

Instead of Long.toHexString I would use Long.parseLong to parse the value and then String.format to output the value with the desired width (21 in your example):


public static String binaryToHex(String bin) {
   return String.format("%21X", Long.parseLong(bin,2)) ;
}

这篇关于Java的:二进制字符串转换为十六进制字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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