如何输出指定位数的二进制或十六进制数

lianglin999 2010-10-26 10:37:13
RT:
例如:

int a = 100;
System.out.println (Integer.toBinaryString (a));


输出是:1100100

而我想的是输出8位的二进制数:01100100

请教该如何实现
...全文
743 12 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
kyo19 2010-10-28
  • 打赏
  • 举报
回复
DecimalFormat df = new DecimalFormat("00000000");

就是指定它的输出格式,如果有数的会显示原来的数字,没有的显示0,你输入的是7位,因为最开始的0被省略了

下面的Integer.valueOf(bin) 是因为通过format出来的是个String类型,但你查看API时df.format(...)中传的没有String这个类型,所以我只是把他转为Int类型而已
thegodofwar 2010-10-26
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 kyo19 的回复:]
Java code
public static void main(String[] args) {
int a = 100;
String bin = Integer.toBinaryString(a);
System.out.println (Integer.toBinaryString (a));
De……
[/Quote]
+1不过为了扩大范围,可以把
String format = df.format(Integer.valueOf(bin));
改为
String format = df.format(Long.valueOf(bin));
Miracle1216 2010-10-26
  • 打赏
  • 举报
回复

public class Test {
public static void main(String[] args) {
int a = 100;
System.out.println(Integer.toBinaryString(a));
System.out.println(convert(Integer.toBinaryString(a), 8));
}

private static String convert(String str, int length) {
if (str.length() < length) {
String temp = "";
for (int i = 0; i < length - str.length(); i++) {
temp += "0";
}
return temp + str;
}
return str;
}
}
kyo19 2010-10-26
  • 打赏
  • 举报
回复
	public static void main(String[] args) {
int a = 100;
String bin = Integer.toBinaryString(a);
System.out.println (Integer.toBinaryString (a));
DecimalFormat df = new DecimalFormat("00000000");
String format = df.format(Integer.valueOf(bin));
System.out.println(format);
}
precious 2010-10-26
  • 打赏
  • 举报
回复
static String getBinaryFromInt(int b) {
StringBuffer sb = new StringBuffer();
for (int i = 7; i >= 0; i--) {
sb.append(((b & (1 << i)) != 0) ? '1' : '0');
}
return sb.toString();
}

输出是:01100100
liudan3319 2010-10-26
  • 打赏
  • 举报
回复
DecimalFormat df=new DecimalFormat("00000000");
System.out.println("ffffffffffffffffffff"+df.format(111111));
result:ffffffffffffffffffff00111111
龙四 2010-10-26
  • 打赏
  • 举报
回复
System.out.printf自己设置格式
liudan3319 2010-10-26
  • 打赏
  • 举报
回复
DecimalFormat
closewbq 2010-10-26
  • 打赏
  • 举报
回复
判断长度,自己补零
lianglin999 2010-10-26
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 kyo19 的回复:]

Java code
public static void main(String[] args) {
int a = 100;
String bin = Integer.toBinaryString(a);
System.out.println (Integer.toBinaryString (a));
System.out.println (Integer.toBinaryString (a));
DecimalFormat df = new DecimalFormat("00000000"); //不知道这个是什么意思,能解释一下吗,看帮助文档也无法理解,谢谢!
String format = df.format(Integer.valueOf(bin)); //还有这一句?
System.out.println(format);
[/Quote]
刚刚学习Java,请指教
zrcvic 2010-10-26
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 ticmy 的回复:]

System.out.printf自己设置格式
[/Quote]+1

用 DecimalFormat 简直浪费!
ETCentury 2010-10-26
  • 打赏
  • 举报
回复
6楼,7楼都不错~!

62,634

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧