Sunday 15 March 2015

java - Representing signed byte in an unsigned byte variable -



java - Representing signed byte in an unsigned byte variable -

i apologies if title of question not clear, cannot figure out best way describe predicament in few words.

i writing communication framework between java , c# using sockets , byte byte transfer of information.

i have ran issue has been confusing me few hours now. know. java's byte base of operations type signed, meaning can store -128 +127 if represent in integer form. c# however, uses unsigned bytes, meaning store 0-255 in integer form.

this encountering issue. if need send bytes of info c# client java server, utilize next code:

c#:

memorystream stream; public void write(byte[] b, int off, int len) { stream.write(b, off, len); }

java:

datainputstream in; public int read(byte[] b, int off, int len) throws ioexception{ in.read(b, off, len)); }

as can see these very similar pieces of code when used within own languages produce predictable results. however, due differences in signing these produce unusable data.

i.e if send 255 c# client java server, receive value of -1 on java server. because both of values represented of these 8 bits: 11111111

preferably in order solve problem need utilize next code, using sbyte, c#'s signed byte.

c#:

memorystream stream; public void write(sbyte[] b, int off, int len) { //code alter sbyte byte keeping in form in java understand stream.write(b, off, len); }

i need store java's representation of signed byte within unsigned c# byte in order send byte across server. need in reverse sbyte out of byte received java server.

i have tried numerous ways in no success. if has thought how can go appreciative.

you don't need except stop thinking bytes numbers. think of them 8 bits, , java , c# identical. it's rare want consider byte magnitude - it's binary info image, or perhaps encoded text.

if want send byte 10100011 across java c# or vice versa, in natural way. bits correct, if byte values different when treat them numbers.

it's not exclusively clear info you're trying propagate, in 99.9% of cases can treat byte[] opaque binary data, , transmit without worrying.

if do need treat bytes magnitudes, need work out range want. it's easier handle java range, c# can back upwards sbyte[]... if want range 0-255, need convert byte int on java side , mask bottom 8 bits:

byte b = ...; int unsigned = b & 0xff;

if need treat byte[] sbyte[] or vice versa on c#, can utilize little secret: though c# doesn't allow convert between two, clr does. need go via conversion of reference object fool c# compiler thinking might valid - otherwise thinks knows best. executes no exceptions:

byte[] x = new byte[] { 255 }; sbyte[] y = (sbyte[]) (object) x; console.writeline(y[0]); // -1

you can convert in other direction in same way.

java c# sockets byte

No comments:

Post a Comment