开发者

Converting a number larger than 255 into a byte variable

I understand the concept of bytes and declaring variables to save on processing space. I understand that the max 开发者_StackOverflow社区value that can be stored in a byte is 255.

I cannot seem to wrap my head around my current issue and was hoping that someone would be able to educate me and help me solve this problem. I don't have much experience working with byte manipulation.

I was given a project to update and was told that the service that is passing data to my project would start using 2bytes to transfer the ID rather than the 1 byte previously as their parameters have grown.

The current declaration for the variable is:

Dim bytvariable As Byte = 0

What is the new declaration to accept a 2 byte value?

Secondly, how would I be able to convert that 2 byte value into an integer number?

Example, they are passing me this value: 0x138 and it is supposed to come out as 312.

Thank you in advance.


Here's a summary of the "primitive" datatypes in .NET, and their sizes.

Yes, an Int16 is probably what you want.

Often you'd be reading the binary data from a stream, or getting it from an array of bytes. To convert from those sources into an Int16, you can do this:

in C#:

byte[] block = new byte[128];
mystream.Read(block, 0, block.Length);
int i = 0;
Int16 value = (Int16)(block[i++] + block[i++] * 256);

In VB.NET, it would be:

Dim block as New Byte(128)
stream.Read(block, 0, block.Length)
Dim i as Int16 = 0
Dim value As Short = CShort((block(i) + (buffer(i+1) * &H100)))
i = i + 2

(I think)


from the top of my head I'd suggest if you insist on doing it that way (instead of just passing an integer), you could use an array of byte, first index holding the first number and the second index the second ex. byte[0] = 123, byte[1] = 255;

then combine them into a string ex. string concatenatedNumber = byte[0].ToString() + byte[1].ToString(); then parse it ex. int ID = Int32.Parse(concatenatedNumber);

Examples are in C#, but I think you should get the idea. I would definitely rather just pass it as an integer though.


You could try this:

Dim bytvariable As Byte(0 To 1)

bytvariable(0) = ' Get the first byte however they are sending it
bytvariable(1) = ' Get the second byte however they are sending it
Dim value As Int16 = BitConverter.ToInt16(buffer, 0);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜