Doorgaan naar hoofdcontent

Posts

Er worden posts getoond met het label new string

Java String toBytes and from Bytes

Last week I was trying to encode some encrypted data as a cookie. After encrypting the data, I was left with a byte[] array. So all that was left was to create a string, and then fix all the strange characters... preferably by base64 encoding it, for example. That worked fine, until I wanted to decode the string. All of a sudden the byte[] array was no longer the same... well, sometimes, it wasn't. byte[] data = new byte[20]; new Random().nextBytes[data]; // fill with some random data. String myString = new String(data); byte[] fromString = myString.getBytes(); for(int i = 0; i < data.length; i++) assert(data[i] == fromString[i]) The code above will fail... from time to time. This is rather strange, and not directly obvious from the javadoc. First I considered if it was an encoding problem. This only compounded the issue, as new String(data, "UTF-16" ).getBytes().length is twice the size of the original data. That was leading nowhere. After lo...