简体   繁体   中英

Converting c# byte to java byte

I'm not realizing what is wrong with my code, take a look:

C# code:

const int MOVE = 112;
MemoryStream m = new MemoryStream();
m.SetLength(4 + 1 + (1 + 1 + 1 + 1));
BinaryWriter bw = new BinaryWriter(m);
int id_ = getId();
bw.Write(Converter.GetBigEndian(id_));
sbyte eventMove = MOVE;
sbyte rowFromByte = 4;
sbyte colFromByte = 2;
sbyte rowToByte = 1;
sbyte colToByte = 3;
bw.Write(eventMove);
bw.Write(rowFromByte);
bw.Write(colFromByte);
bw.Write(rowToByte);
bw.Write(colToByte);

When I read on java I do:

ByteBuffer msg = an instance of ByteBuffer...
int id = msg.getInt();
byte event = msg.get();
byte rowFrom = msg.get();
byte colFrom = msg.get();
byte rowTo = msg.get();
byte colTo = msg.get();

Every time I read on java it reaches till the event ok.

Sometimes it works correctly, reads everything ok eg if I put on c#:

sbyte rowFromByte = 12;
sbyte colFromByte = 2;
sbyte rowToByte = 1;
sbyte colToByte = 3;

It works, but if I put a value <= 7 on the first rowFromByte eg:

sbyte rowFromByte = 4;
sbyte colFromByte = 2;
sbyte rowToByte = 1;
sbyte colToByte = 3;

the java code doesn't read the values correctly it reads:

rowFrom: -7, colFrom: 0, rowTo: -7, colTo: 0

SOLVED: the values above were printed wrongly (during the wrong time), because of that I thought there were problems with the code. It prints the corrects values bellow:

 rowFrom: 4, colFrom: 2, rowTo: 1, colTo: 3

On c# I use the Memorystream to get the bytes to send to java client:

MemoryStream message = the instance of memory stream...
bytesMessage = message.ToArray();

WHY putting a value <= 7 for rowFrom returns wrong bytes association on java?

There's something very weird or silly I'm not getting into.

I solved the problem.

The problem is that: there wasn't any problem with my code .

As I supposed this was a Silly stuff: I was printing the wrong variables on server.

I didn't know very well C# I posted this question on on stackoverflow. Maybe this simple example can be useful for other people.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM