programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Converting String to Integer without losing leading zero's

John Gable
Greenhorn
Posts: 11
Hey,

I'm trying to convert a 8 bit string of binary into an integer.
I do this by

Only problem is it drops the leading zeros.
eg if the string rep was 00111001 then after parsing the Integer represents 111001 -> i need the extra 0's at the front to make it 8 bits.

How can i keep them?? or add them in later to an Integer?

Jeanne Boyarsky
author & internet detective
Marshal
Posts: 37462
537
John,
An Integer just represents a value. 5 = 05 = 005
These are all equivalent and so should be represented by the same Integer value.

John Gable
Greenhorn
Posts: 11
I'm trying to do an encryption algorithm - for the decryption it requires 8 bits -> if i pass in only 6 as in this example it doesnt like it.

Paul Clapham
Sheriff
Posts: 22823
43
Your question here about passing "bits" doesn't seem to have anything to do with the original question about preserving leading zeroes in integers. If you're having a problem with the number of bits you're passing, then you must not be passing an integer. Would you like to display the code you're using to pass those bits?

John Gable
Greenhorn
Posts: 11
Ok I've done some checking.

This is the code i modified to check what was being passed in.

Looking at the result from the 2nd one:

inside decrypt for printb

that means it's not passing in the 00001111 that i want - but 585.
not sure where 585 is coming from tho ?

Ilja Preuss
author
Sheriff
Posts: 14112
An integer literal that starts with a zero is in octal. 1111 octal is 585 decimal.

John Gable
Greenhorn
Posts: 11
So how to i get the integer to store 00001111 ??

Martin Simons
Ranch Hand
Posts: 196
What you are doing requires a bitstring not an integer.
If you really need to convert this bitstring to an integer
then you need to do Integer.parseInt(string, 2) ;

What you probably should do, if you really need to pass
an integer, rather than the bitstring in string form is
to pass the number as shown above and then, inside the
routine that is going to use it do Integer.toBinaryString( ) ;

Ilja Preuss
author
Sheriff
Posts: 14112
Originally posted by John Gable:
So how to i get the integer to store 00001111 ??

As 1111 binary is 15 decimal

int ans1 = 15;

int ans1 = Integer.parseInt("00001111", 2);

which should lead to exactly the same result.

An int has a fixed number of bits, so you can't tell it how many leading zeros it should have. If you really need that information, you can't store it in an int.

Keith Lynn
Ranch Hand
Posts: 2409
Can you show us the method that requires the integer like that?