Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Get back leading zeros!

2,312 views
Skip to first unread message

Giovanni D'Ascola

unread,
Jan 11, 2008, 2:12:11 PM1/11/08
to
Hi

The method Integer.toHexString(int i) convert his argument to a string
of ASCII digits in hexadecimal (base 16) with no extra leading 0s.

Good, but... i need those extra leading 0s! How to get back them?!
Help!

Message has been deleted

Giovanni D'Ascola

unread,
Jan 11, 2008, 2:23:06 PM1/11/08
to Stefan Ram
Stefan Ram ha scritto:
> "00" + Integer.toHexString( i )?
>
Yes!

Knute Johnson

unread,
Jan 11, 2008, 2:48:18 PM1/11/08
to

If you want them to have the same number of characters you can use a
Formatter.

public class test6 {
public static void main(String[] args) {
System.out.println(String.format("%04x",0x2a));
}
}

--

Knute Johnson
email s/nospam/knute/

--
Posted via NewsDemon.com - Premium Uncensored Newsgroup Service
------->>>>>>http://www.NewsDem

Roedy Green

unread,
Jan 11, 2008, 4:11:21 PM1/11/08
to
On Fri, 11 Jan 2008 20:12:11 +0100, Giovanni D'Ascola
<giovanni...@gmail.cm> wrote, quoted or indirectly quoted someone
who said :

>
>Good, but... i need those extra leading 0s! How to get back them?!

see http://mindprod.com/jgloss/hex.html
--
Roedy Green, Canadian Mind Products
The Java Glossary, http://mindprod.com

Lord Zoltar

unread,
Jan 11, 2008, 4:29:23 PM1/11/08
to
On Jan 11, 2:12 pm, Giovanni D'Ascola <giovanni.dasc...@gmail.cm>
wrote:

Sounds like you need a good string padding function

StringBuffer paddedString = new StringBuffer(str);
if (finalLength>0 && finalLength>str.length())
{
int padLength = finalLength - str.length();
char padding[] = new char[padLength];
Arrays.fill(padding, padChar);

if (padLeft)
paddedString.insert(0, padding);
else
paddedString.append(padding);
}

return paddedString.toString();

Mark Space

unread,
Jan 11, 2008, 4:30:32 PM1/11/08
to
Knute Johnson wrote:

> If you want them to have the same number of characters you can use a
> Formatter.
>
> public class test6 {
> public static void main(String[] args) {
> System.out.println(String.format("%04x",0x2a));
> }
> }
>

I was thinking a new type which remembers the number of digits in the
original and recreates it on output.

class MyHex {
int width;
int value;

public MyHex( String s ) {
// Count some hex digits, maybe the leading 0x should be removed?
width = s.length(); // TODO: Too simple by far....
value = Integer.parseInt( s, 16 );
}

public String toString() {
String formatString = "%0" + width + "x";
return String.format( formatString, value );
}
}

All this totally off the top of my head, I didn't check the APIs at all.
Also not it's syntax checked. This is just a general outline. And
MyHex should probably extend Number, but I didn't look into that either....

0 new messages