byte array to string conversion

Lars Andersen lars@rimfaxe.com
Thu Sep 11 16:36:00 GMT 2003


In the Mysql jdbc driver I discovered a byte[] to string conversion 
utility that does not work with GCJ.

I made a little test program, maybe someone can tell what's going on.

With Sun jdk 1.4.1 on linux it outputs "toAsciiString -> Test String"

With GCJ 3.3 on linux it outputs "toAsciiString -> "

 >>>>>>>>>>>>>>>>>>>

public class TestStringConversion
{
    private static final int BYTE_RANGE = (1 + Byte.MAX_VALUE) - 
Byte.MIN_VALUE;
    private static byte[] allBytes = new byte[BYTE_RANGE];
    private static char[] byteToChars = new char[BYTE_RANGE];

    static {
        for (int i = Byte.MIN_VALUE; i <= Byte.MAX_VALUE; i++) {
            allBytes[i - Byte.MIN_VALUE] = (byte) i;
        }

        String allBytesString = new String(allBytes, 0,
                Byte.MAX_VALUE - Byte.MIN_VALUE);

        int allBytesStringLen = allBytesString.length();

        for (int i = 0;
                (i < (Byte.MAX_VALUE - Byte.MIN_VALUE))
                && (i < allBytesStringLen); i++) {
            byteToChars[i] = allBytesString.charAt(i);
        }
    }
   
    public TestStringConversion()
    {
    }
   
    /**
     * String conversion as found in com.mysql.jdbc.StringUtils
     */
    public static String toAsciiString(byte[] buffer, int startPos, int 
length)
    {
        char[] charArray = new char[length];
        int readpoint = startPos;
        for (int i = 0; i < length; i++)
        {
            charArray[i] = byteToChars[(int) buffer[readpoint] - 
Byte.MIN_VALUE];
            readpoint++;
        }
        return new String(charArray);
    }
   

    public static void main(String[] args)
    {    
       String test_str = "Test String"; 
       byte[] test_buf = test_str.getBytes();
       System.out.println("toAsciiString -> "+toAsciiString(test_buf, 0, 
test_buf.length));
    }
   
}

<<<<<<<<<<<<<<<<<<<


/Lars Andersen



More information about the Java mailing list