This is the mail archive of the java@gcc.gnu.org mailing list for the Java project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: byte array to string conversion


Tom Tromey wrote:

"Lars" == Lars Andersen <lars@rimfaxe.com> writes:



Lars> Just tried it with the latest 3.4 snapshot. Same thing.


I suspect your system's iconv(), or your locale setting, or both.

Try debugging the program with gdb.  My theory is that the early
`test_str.getBytes()' call is returning bad results.

Tom



I modified the example a bit.


This one works for both Sun jdk and GCJ.

Substitute "iso-8859-1" with "UTF-8" and only Sun jdk works (at least for me)

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

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 = "";
try
{
allBytesString = new String(allBytes,0,Byte.MAX_VALUE - Byte.MIN_VALUE,"iso-8859-1");
}
catch (Exception e)
{ }
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


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]