Re: String of numbers into to array of numbers
bH wrote:
Hi All,
Here are 2 attempts to get it correct.
I might be a bit confused as to what you are trying to do. Does all
this just change strings into ints? You seem to be doing a lot of work
here when you could just be calling an existing String method.
I did a version last week, thinking I understood what problem statement
was. All I did was call "getBytes()". If I understand correctly, that
one call replaces most of your first program.
Rather than use Roedy's routine, I just wrote my own. Here's my
attempt. It's not very good. It has no Java doc, I use number literals
rather than declaring constants, and I just read the Wikipedia entry and
implemented their example. A real implementation would need to code
carefully to the RFCs and would need a lot more unit testing.
However, if you read the main method, you can see that my test is quite
short. I use the four strings that Wikipedia provides encodings for,
and check them myself for correctness. To turn strings into arrays of
bytes, I just call getBytes() as I mentioned.
If I understand the problem correctly, you are trying to implement
"decode" as below. (Mine's not done.) Is that true?
package local;
public class Base64
{
private static final String alphabet64 =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
// Base64 is final and non-instantiable only.
// DO NOT CHANGE THIS.
private Base64()
{
}
public static String encode( byte[] b )
{
StringBuilder sb = new StringBuilder(
b.length*4/3+b.length/48*4+6 );
for( int i = 0; i<b.length; )
{
// 1
int base = (b[i]>>>2)&0x3F;
sb.append( alphabet64.charAt( base ) );
if( i+1<b.length )
{
// 2
base = (b[i]<<4)&0x30|(b[i+1]>>>4)&0xF;
sb.append( alphabet64.charAt( base ) );
if( i+2<b.length )
{
// 3
base = (b[i+1]<<2)&0x3C|(b[i+2]>>>6)&0x3;
sb.append( alphabet64.charAt( base ) );
// 4
base = b[i+2]&0x3F;
sb.append( alphabet64.charAt( base ) );
}
else
{
// 3, no third byte
base = (b[i+1]<<2)&0x3C;
sb.append( alphabet64.charAt( base ) );
sb.append( "=" );
}
}
else
{
// 2, no second byte
base = (b[i]<<4)&0x30;
sb.append( alphabet64.charAt( base ) );
sb.append( "==" );
}
i+= 3;
// if( i % 48 == 0 ) {
// sb.append( '\n' );
// }
}
return sb.toString();
}
public static byte[] decode( String s )
{
return new byte[1];
}
public static void main( String... args )
{
String test[] =
{
"leasure.",
"leasure",
"leasur",
"leasu",
"Man is distinguished, not only by his reason"
};
for( String testString : test )
{
String enc = encode( testString.getBytes() );
System.out.println( "The string:\n"+testString+
"\n\nis encoded as:\n"+enc+"\n" );
}
}
}