好办法,短期和字节之间转换? [英] Good way to convert between short and bytes?

查看:159
本文介绍了好办法,短期和字节之间转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要对以字节为单位,输出短路,走在短裤和输出字节对。以下是我已经设计了这样一个目的的功能:

I need to take pairs of bytes in, and output shorts, and take shorts in and output pairs of bytes. Here are the functions i've devised for such a purpose:

static short ToShort(short byte1, short byte2)
{
    short number = (short)byte2;
    number <<= 4;
    number += (short)byte1;
    return number;
}
static void FromShort(short number, out byte byte1, out byte byte2)
{
    byte byte2 = (byte)(number >> 4);
    short tempByte = (short)byte2 << 4;
    byte byte1 = (byte)(number - tempByte);
}

我认为这是正确的,但我不知道。如果这不是正确的方式做到这一点,是什么?是有办法的框架已经做到这一点?

I think this is correct but i'm not sure. If this isn't the right way to do it, what is? is there a way to do this already in the framework?

推荐答案

更​​短的版本(也移位8位而不是4):

Shorter version (also shifting 8 bits instead of 4):

static short ToShort(short byte1, short byte2)
{
    return (byte2 << 8) + byte1;
}

static void FromShort(short number, out byte byte1, out byte byte2)
{
    byte2 = (byte)(number >> 8);
    byte1 = (byte)(number & 255);
}

这篇关于好办法,短期和字节之间转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆