相关疑难解决方法(0)

C#中的OR-ing字节给出了int

我有这个代码.

byte dup = 0;
Encoding.ASCII.GetString(new byte[] { (0x80 | dup) });
Run Code Online (Sandbox Code Playgroud)

当我尝试编译时,我得到:

无法将类型'int'隐式转换为'byte'.存在显式转换(您是否错过了演员?)

为什么会这样?不应该| 两个字节给出一个字节?以下两项工作,确保每个项目都是一个字节.

Encoding.ASCII.GetString(new byte[] { (dup) });
Encoding.ASCII.GetString(new byte[] { (0x80) });
Run Code Online (Sandbox Code Playgroud)

c# logic byte types bit-manipulation

4
推荐指数
2
解决办法
2531
查看次数

为什么7/3不总是int?为什么它可以分配到字节或短,而x/3不能?

我认为任何算术表达式的结果至少是一个int.7/3是一个表达式 - 它有一个运算符(除法).

但为什么编译好呢?

byte b1 = 7 / 3;     // 7/3 is not a literal?
short b2 = 7 / 3;    // 7/3 is not a literal?
char b3 = 7 / 3;     // 7/3 is not a literal?
Run Code Online (Sandbox Code Playgroud)

和f1()编译好吗?

byte f1() {
    return 7 / 3;    // Why is it allowed?  Why isn't 7 / 3 an int ?
}

byte f2(int x) {
    return x / 3;   // c.ERR - type mismatch
}

byte f3(byte x) { …
Run Code Online (Sandbox Code Playgroud)

java

4
推荐指数
1
解决办法
177
查看次数

标签 统计

bit-manipulation ×1

byte ×1

c# ×1

java ×1

logic ×1

types ×1