c++ - C++中char和unsigned char的按位比较

标签 c++ comparison bit-manipulation

<分区>

为什么 C++ 中没有像“====”这样的按位比较器?我每次都必须转换变量吗?

(注意:我已经知道逻辑算术运算符,看起来不同。顺便说一下,也没有算术异或 a^^b :) 我知道我可以检查 a&b 与 a(或 b),a^b 与零,... )

#include "stdafx.h"
#include<iostream>
#include<stdlib.h>

int main()
{
    char a=-1;
    unsigned char b=0;

    for(b=0;b<255;b++)
    {
        if(a==b)std::cout<<(int)b;  //cannot find 11111111)2==11111111)2
                                    //ok, it looks -1==255 surely 
                  //if(a====b)std::cout<<" bitwise equal "; could be good
    }



    bool compare=true;
    bool bit1=false,bit2=false;
    unsigned char one=1;

    b=255; //bit-swise equal to a
    for(int i=1;i<7;i++)
    {
        bit1=(a>>i)&one;
        bit2=(b>>i)&one;
        if(bit1!=bit2){compare=false;return;}//checks if any bit is different 
    }

    if(compare)std::cout<<(int)b; //this writes 255 on screen

    getchar();
    return 0;
}

谢谢。

我本可以做到:

__asm
     {
          push push....
          mov al,[a]
          mov dl,[b]
          cmp al,dl    //this is single instr but needs others
          je yes       
          mov [compare],false
          jmp finish
          yes:
          mov [compare],true
          jmp finish

          finish:
          pop pop...

臃肿的代码...

最佳答案

这样的运算符是行不通的,因为它依赖于平台。

我假设当 x 和 y 的长度不同时,'x === y' 应该返回 false,并且由于 int 在不同平台上具有不同的长度,因此此操作的结果也是如此。

关于c++ - C++中char和unsigned char的按位比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12276248/

相关文章:

c++ - Visual Studio 2015/Linux 扩展使用 Cygwin 生成 "collect2 : error : ld returned 1 exit status"

c++ std::sort() 的自定义比较函数

c++ - 如何在不使用 std::forward 的情况下调用成员变量的 move 构造函数?

java - 如何比较两个 list<t> 对象?

c# - 将 java 方法转换为 C# : converting bytes to integers with bit shift operators

python - 在 Python 中读取最低有效位

c++ - 在不同处理器之间共享内存时需要哪些东西?

Python多重比较风格?

algorithm - 计算人类如何感知不同颜色之间的相似性

objective-c - 在 NS_OPTIONS 中测试多个标志或条件