• Post Reply Bookmark Topic Watch Topic
  • New Topic

Java encoding...  RSS feed

 
Nev Mehta
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

I need to write a byte stream onto the network, what i plan to do is take the byte arrays i have, convert them to a string and recreate the byte array using the string i receive on the other end.

Let me illustrate my problem...

1. bss is what i wish to transfer
byte bss[] = new byte[1];
bss[0] = (byte) (129 & 0xff);
System.out.println("Byte value: " + bss[0]);
System.out.println("Int value: " + ( bss[0] & 0xff ));

2. convert bss to a string
StringBuffer ston = new StringBuffer();
ston.append(new String(bss,"UTF-8"));

3. Recreate bss from string
System.out.println(ston.toString());
byte bss2[] = ston.toString().getBytes();
System.out.println("Byte value: " + bss2[0]);
System.out.println("Int value: " + ( bss2[0] & 0xff ));

For some reason my output is:-
Byte value: -127
Int value: 129
?
Byte value: 63
Int value: 63

I need the same byte value and int value after recreating the bytes using getBytes(), i think there is some issue with the encoding issues coming up, wondering if anyone knows a fix for what i'm trying to do..

Thanks
Neville
 
Pat Farrell
Rancher
Posts: 4686
7
Linux Mac OS X VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Don't send bytes.

Take the byte[] and use mime encoding to convert it to characters.
Then send the Strings across the network.

Its nearly impossible to keep the big-endian and little-endian stuff correct when sending binary.
 
Nev Mehta
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Thanks for the reply, well the issue here is that I'm trying to develop a network application that would be working with similar network app's made by other people, and those network app's would be expecting raw bytes to be sent to them. They wouldnt be aware that i have encoded this data using MIME.

Any other solution?

Thanks
Neville
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!