简体   繁体   中英

Convert byte[] buf[offset] to int16

I'm getting a compile error

"Unable to convert int to short".

Any ideas?

public Int16 GetInt16(byte[] buf, int offset)
{
    Int16 value = 0;

    value += buf[offset] << 8;

    return value;
}

You need to explicitly cast or convert it. eg

value += Convert.ToInt16(buf[offset] << 8)

Use BitConverter.ToInt16(buffer, starting index). This will do the job for you and you do not have to reinvent the wheel. This also helps prevent accidently code errors (besides the starting index). (yes this is a little different solution to the question but does the same job in a more robust manner).

Documentation: http://msdn.microsoft.com/en-us/library/system.bitconverter.toint16.aspx

Edit:

This will not work in your specific case because you use one byte. If you had the buffer and the two bytes would equal the int16 then you would have the correct data.

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