简体   繁体   English

Java中的String.format()和十六进制数字

[英]String.format() and hex numbers in Java

I'm trying to figure out why String.format() is behaving the way it does. 我试图找出为什么String.format()的行为方式。

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. 目标文件中有一个5字符的十六进制字段,我从一个值创建。

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

This works as intended for positive numbers (11 -> 0000B ) However it fails for negative numbers (-1 -> FFFFFFFF instead of FFFFF ) 这适用于正数(11 - > 0000B )但是它不能用于负数(-1 - > FFFFFFFF而不是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. 我想我可以只取最后5个字符的子字符串,但我还是想弄清楚它为什么会这样。

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);

Format width only works to create a minimum number of digits, and only has effect on leading zeroes. 格式宽度仅适用于创建最小位数,并且仅对前导零有影响。

Instead of substring, you could use a bit mask: 您可以使用位掩码代替子字符串:

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

By the way, 11 -> 0000B , not 0000A as claimed in your question. 顺便说一句, 11 - > 0000B ,而不是你问题中声称的0000A

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM