按位运算符和有符号类型

按位运算符和有符号类型

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

问题描述

我正在阅读C ++ Primer,我对一些评论感到有些困惑,这些评论谈论按位运算符如何处理带符号的类型.我会引用:

I'm reading C++ Primer and I'm slightly confused by a few comments which talk about how Bitwise operators deal with signed types. I'll quote:

引用#1

引用#2

按位运算符将小整数(例如char)提升为有符号整数.当按位运算符经常对带符号运算符类型给出未定义或实现定义的行为时,此提升为 signed int是否存在问题?为什么标准不将char提升为unsigned int?

The bitwise operators promote small integers (such as char) to signed ints. Isn't there an issue with this promotion to signed ints when bitwise operators often gives undefined or implementation-defined behaviour on signed operator types? Why wouldn't the standard promote char to unsigned int?

这是我提出的问题,但是我将其放回了背景,下面给出了一些答案.

Here is the question I took out, but I've placed it back for context with some answers below.

稍后要进行练习

在具有32位int s和8位char s的计算机上,~'q' << 6的值是什么,该计算机使用Latin-1字符集,其中'q'的位模式为01110001 ?"

"What is the value of ~'q' << 6 on a machine with 32-bit ints and 8 bit chars, that uses Latin-1 character set in which 'q' has the bit pattern 01110001?"

好吧,"q"是一个字符文字,会提升为int,即给出

Well, 'q' is a character literal and would be promoted to int, giving

~'q' == ~0000000 00000000 00000000 01110001 == 11111111 11111111 11111111 10001110

下一步是对上述位应用左移运算符,但正如 quote#1 所提到的

The next step is to apply a left shift operator to the bits above, but as quote #1 mentions

我不完全知道符号位是哪一位,但是答案肯定是不确定的吗?

well I don't exactly know which bit is the sign bit, but surely the answer is undefined?

推荐答案

您是正确的-根据标准,表达式~'q' << 6是未定义的行为.它甚至比您指出的还要糟糕,因为~运算符被定义为计算值的一个补码",这对于有符号(2s补码)整数毫无意义-术语一个补码"实际上仅表示任何含义表示无符号整数.

You're quite correct -- the expression ~'q' << 6 is undefined behavior according to the standard. Its even worse than you state, as the ~ operator is defined as computing "The one's complement" of the value, which is meaningless for a signed (2s-complement) integer -- the term "one's complement" only really means anything for an unsigned integer.

在进行按位运算时,如果要严格定义(根据标准)结果,则通常必须确保操作的值是无符号的.您可以通过显式强制转换或在二进制操作中使用显式无符号常量(U-后缀)来实现.使用有符号和无符号int进行二进制操作是作为无符号完成的(将有符号值转换为无符号).

When doing bitwise operations, if you want strictly well-defined (according to the standard) results, you generally have to ensure that the values being operated on are unsigned. You can do that either with explicit casts, or by using explicitly unsigned constants (U-suffix) in binary operations. Doing a binary operation with a signed and unsigned int is done as unsigned (the signed value is converted to unsigned).

C和C ++在整数提升方面有细微的差别,因此您在这里需要小心-C ++在与其他操作数进行比较之前应将小于int的无符号值转换为int(有符号)完成,而C将首先比较操作数.

C and C++ are subtley different with the integer promotions, so you need to be careful here -- C++ will convert a smaller-than-int unsigned value to int (signed) before comparing with the other operand to see what should be done, while C will compare operands first.

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

07-30 15:21