Java中的String.format()和十六进制数字 [英] String.format() and hex numbers in Java

查看:999
本文介绍了Java中的String.format()和十六进制数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清楚为什么 String.format()的行为是这样的。

上下文:系统编程类,编写一个汇编程序。

目标文件中有一个5字符的十六进制字段,我从一个值创建。


$ b

尝试使用: String.format(%05X,decInt);



这可以按正数运行
(11 - > 0000B
然而,对于负数
( - 1 - > FFFFFFFF 而不是 FFFFF


假设我可以只接受最后5个字符的子字符串,但是我仍然想知道为什么会这样。

解决方案

格式中使用的宽度始终是最小宽度。在这种情况下,而不是使用子字符串操作,我会建议:

  String.format(%05X,decInt&的0xFFFFF); 


I'm trying to figure out why String.format() is behaving the way it does.

Context: Systems programming class, writing an assembler.

There is a 5 character hex field in the object file, which I am creating from a value.

Tried using: String.format("%05X", decInt);

This works as intended for positive numbers (11 -> 0000B) However it fails for negative numbers (-1 -> FFFFFFFF instead of FFFFF)

I suppose I could just take a substring of the last 5 characters, but I would still like to figure out why it behaves this way.

解决方案

The width used in format is always a minimum width. In this case, instead of using sub string operations I would suggest:

  String.format("%05X", decInt & 0xFFFFF);

这篇关于Java中的String.format()和十六进制数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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