字节的按位运算符? [英] Bitwise operators for bytes?

查看:106
本文介绍了字节的按位运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C#的新手,并且在位操作方面遇到了一些麻烦.
我有两个字节.我要做的第一件事是通常将数据移动到四个字节中的一个字节中,我通常会这样做.

字节1 = 00001111
字节1 =字节1<< 4
字节1 = 11110000

但是,这似乎仅适用于整数吗?
一旦我转移了数据,我想像这样将它们加在一起.

字节1 = 11110000

字节2 = 00001111

字节加在一起= 11111111

最好的方法是什么?

谢谢.

Hi, I''m new to C# and I''m having some trouble with bit manipulation.
I have Two bytes. The first thing i want to do is to shift the data in one of the bytes four places normally i would do it like this.

byte1 = 00001111
byte1 = byte1 << 4
byte1 = 11110000

however, this seems to work only for integers?
once i have shifted the data i would like to add them together like this.

byte 1 = 11110000

byte 2 = 00001111

bytes added together = 11111111

What is the best way of doing this?

Thank you.

推荐答案

之所以抱怨,是因为按位运算符仅针对整数和布尔值(而非字节)定义,因此它们都首先被提升.只需将它们退回,就可以了.
The reason it complains it that the bitwise operators are defined for integer and bool only, not byte, so they all get promoted first. Just cast them back, and you''ll be fine.
byte b1 = (byte) 0xF0;
byte b2 = 0x0F;
byte b3 = (byte)(b2 << 4);
byte b4 = (byte) (b1 ^ b3);
MessageBox.Show(string.Format("{0}, {1}, {2}, {3}", b1, b2, b3, b4));

^将它们异或,+添加,|.是OR和&是AND.

^ XORs them together, + adds, | is OR and & is AND.


byte1 <<= (byte)4;

使用VS2008在我的机器上工作.

您会遇到运行时错误,还是无法编译?
byte1 <<= (byte)4;

Works on my machine using VS2008.

Do you get an run-time error, or will it not compile?


这篇关于字节的按位运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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