tags:

views:

74

answers:

2

Hello,

Lets say I have a number 345, I want to have so that I end up with 0345. I.e.

int i = 0345;

How can I take an existing number and shift it along or append a 0.

Thanks

+1  A: 

Using a 0 on the start of the number when declaring it means it's octal, so 0345 is actually 229 in decimal. I'm not sure how you expect to add a zero to a number using bitwise operations, which work on the binary representation of the number. If you want to add it to the decimal representation, it won't mean anything, since the number is always stored in binary, and the value is converted for your convenience to decimal when being displayed. When doing any computations, the decimal value is not important, only the binary one.

If you're interested only in displaying the value with a 0 at the start, then you could append the 0 to a String containing that number which can be easily done like this "0" + i.

Andrei Fierbinteanu
needs to be an int.
James moore
I have Integer.parseInt("0"+575,8);, but its a little dirty.
James moore
primitive values cannot contain preceding 0's like that. The value for 345 will actually be `00000000000000000000000101011001`. That's what is used in all computations. When you actually see 345 the system gets this binary value and transforms it into a string to display. Otherwise it's always used like this. Adding a 0 to the decimal representation makes no sense here, you can only add it to the string value. 0345 and 345 would be identical in binary (the 0 in decimal doesn't add anything to the binary value). Perhaps make your question a little clearer if I didn't understand what you want?
Andrei Fierbinteanu
`Integer.parseInt("345")` and `Integer.parseInt("0345")` both return the exact same value (345). The preceding 0 doesn't do anything here.
Andrei Fierbinteanu
`int i = Integer.parseInt("0"+575,8);` and `int i = 0575;` are equivalent (as is `int i = Integer.parseInt("575",8);`). As A.F. stated, integer literals beginning with 0 are interpreted as octal (radix 8), which is the same thing that your parseInt method is doing.
super_aardvark
+3  A: 

I know you are talking about an int, but maybe what you want is to pad a number with leading 0s. A quick way is with the String.format static method.

int num = 345;    
String.format("%04d", num);

would return:

"0345"

The 4d tells it to add 0s to the left if it has less than 4 digits, so you can change it to a 5 and it would give you:

"00345"
Hiro2k