在一个字节中合并2个数字 [英] Combine 2 numbers in a byte

查看:92
本文介绍了在一个字节中合并2个数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数字(从0-9开始),我想将它们合并为1个字节.1号将占用0-3位,而2号将占用4-7位.

I have two numbers (going from 0-9) and I want to combine them into 1 byte. Number 1 would take bit 0-3 and Number 2 has bit 4-7.

示例:我有3和4.
3 = 0011,而4为0100.
结果应为0011 0100.

Example : I have number 3 and 4.
3 = 0011 and 4 is 0100.
Result should be 0011 0100.

如何用这些二进制值组成一个字节?

How can I make a byte with these binary values?

这是我目前拥有的:

    public Byte CombinePinDigit(int DigitA, int DigitB)
    {
        BitArray Digit1 = new BitArray(Convert.ToByte(DigitA));
        BitArray Digit2 = new BitArray(Convert.ToByte(DigitB));

        BitArray Combined = new BitArray(8);
        Combined[0] = Digit1[0];
        Combined[1] = Digit1[1];
        Combined[2] = Digit1[2];
        Combined[3] = Digit1[3];  

        Combined[4] = Digit2[0];
        Combined[5] = Digit2[1];
        Combined[6] = Digit2[2];
        Combined[7] = Digit2[3];
    }

使用此代码,我有ArgumentOutOfBoundsExceptions

With this code I have ArgumentOutOfBoundsExceptions

推荐答案

忘记所有的位数组内容.

Forget all that bitarray stuff.

只需执行以下操作:

byte result = (byte)(number1 | (number2 << 4));

并把它们找回来:

int number1 = result & 0xF;
int number2 = (result >> 4) & 0xF;

这可以通过使用<< >> 位移运算符来实现.

This works by using the << and >> bit-shift operators.

创建字节时,我们将 number2 左移4位(它将结果的最低4位填充为0),然后将 | 用作或那些具有 number1 不变位的位.

When creating the byte, we are shifting number2 left by 4 bits (which fills the lowest 4 bits of the results with 0) and then we use | to or those bits with the unshifted bits of number1.

在还原原始数字时,我们将反向进行此过程.我们将字节向右移位4位,这会将原始的 number2 放回其原始位置,然后使用&0xF 屏蔽其他位.

When restoring the original numbers, we reverse the process. We shift the byte right by 4 bits which puts the original number2 back into its original position and then we use & 0xF to mask off any other bits.

number1 的这些位将已经位于正确的位置(因为我们从未移动过它们),因此我们只需要屏蔽掉其他位,再次使用&0xF .

This bits for number1 will already be in the right position (since we never shifted them) so we just need to mask off the other bits, again with & 0xF.

在执行此操作之前,您应该验证数字是否在0..9范围内;或者(如果您不在意它们是否超出范围,则可以通过与0xF相乘将其限制为0..15).:

You should verify that the numbers are in the range 0..9 before doing that, or (if you don't care if they're out of range) you can constrain them to 0..15 by anding with 0xF:

byte result = (byte)((number1 & 0xF) | ((number2 & 0xF) << 4));

这篇关于在一个字节中合并2个数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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