Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert 2 bytes to a number

I have a control that has a byte array in it.

Every now and then there are two bytes that tell me some info about number of future items in the array.

So as an example I could have:

...
...
Item [4] = 7
Item [5] = 0
...
...

The value of this is clearly 7.

But what about this?

...
...
Item [4] = 0
Item [5] = 7
...
...

Any idea on what that equates to (as an normal int)?

I went to binary and thought it may be 11100000000 which equals 1792. But I don't know if that is how it really works (ie does it use the whole 8 items for the byte).

Is there any way to know this with out testing?

Note: I am using C# 3.0 and visual studio 2008

like image 824
Vaccano Avatar asked Apr 17 '10 22:04

Vaccano


People also ask

How do you convert bytes to numbers?

A byte value can be interchanged to an int value using the int. from_bytes() function. The int. from_bytes() function takes bytes, byteorder, signed, * as parameters and returns the integer represented by the given array of bytes.

How do you represent 2 bytes?

2 bytes would be 4 decimal digits and you could represent values between 0 up to 10000 (not included).

How many characters is 2 bytes?

a character in binary is a series of 8 on or offs or 0 or 1s. one of those is a bit and 8 bits make a byte so 1 byte is one character.so 2 bytes hold two characters.

What is a 2-byte integer?

2-byte signed Integer [the ~] noun – An automation integer data type that can be either positive or negative. The most significant bit is the sign bit, which is 1 for negative values and 0 for positive values. The storage size of the integer is 2 bytes. A 2-byte signed integer can have a range from -32,768 to 32,767.


1 Answers

You say "this value is clearly 7", but it depends entirely on the encoding. If we assume full-width bytes, then in little-endian, yes; 7, 0 is 7. But in big endian it isn't.

For little-endian, what you want is

int i = byte[i] | (byte[i+1] << 8);

and for big-endian:

int i = (byte[i] << 8) | byte[i+1];

But other encoding schemes are available; for example, some schemes use 7-bit arithmetic, with the 8th bit as a continuation bit. Some schemes (UTF-8) put all the continuation bits in the first byte (so the first has only limited room for data bits), and 8 bits for the rest in the sequence.

like image 80
Marc Gravell Avatar answered Sep 28 '22 05:09

Marc Gravell