login about faq

Due to the large amount of spam accounts, we temporarily disabled new user sign ups. To override this, email newuser.lgqa@gmail.com and an admin will determine if you are permitted to join


Hey,

This question is for the developers/everyone who knows about binary conversion on Lockergnome.net

I am currently having trouble with a custom network library which I plan to use for a lower data usage and therefore faster data transmission. It has to work on both C# and Java so therefore I will not be using any build in classes like BitConverter(C#).

My problem basically is that my numbers aren't being converted the way they should. When I pass a short with an value of 500 it returns 2 bytes of the values 244 and 0. This represents the short 244 not 500. With a value of 512 it returns 2 zero's

My current code in C#

short num = 500;

byte offset = 0xff;
byte b1 = (byte)(offset & num); // 244
byte b2 = (byte)((offset & num) >> 8); // 0, should be 1 since (1 * 256) + 244 = 500

//short has been converted to bytes (the wrong way)

short s = b1; // 244
s = (short)(s << b2); // 244 (didn't add anything for the 0 byte which is correct)

It doesn't matter which type of endian it uses as long as it transmits and receives the right data.

What am I doing wrong?

asked Feb 19 '11 at 19:01

nitrocrime's gravatar image

nitrocrime
3.6k6277125


A right shift by 8 is equal to a division by 256, so (0xff & num) >> 8 is always 0. In fact, 0xff >> 8 is always 0. What makes you think otherwise?

Do the shifting before the & operation. Heck, you don't even need the & operation for this! The integers will wrap..

ushort val = 0xf00d;
byte x = (byte)val;
byte y = (byte)(val >> 8);

... or using division instead:

ushort val = 0xf00d;
byte x = (byte)val;
byte y = (byte)(val / 256);

answered Jun 18 '11 at 10:55

beStoN's gravatar image

beStoN
216239

Your answer
toggle preview

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Markdown Basics

  • *italic* or __italic__
  • **bold** or __bold__
  • link:[text](http://url.com/ "title")
  • image?![alt text](/path/img.jpg "title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported


Join Us in the Chat Room

Tags:

×893
×311
×133
×125
×54
×17
×16
×15
×4
×3
×3
×2
×1

Asked: Feb 19 '11 at 19:01

Seen: 1,088 times

Last updated: Jun 18 '11 at 10:55