gpt4 book ai didi

c++ - 类型安全和 NEG 指令

转载 作者:搜寻专家 更新时间:2023-10-31 01:39:42 33 4
gpt4 key购买 nike

我需要移植这个汇编指令:

NEG eax

所以我做了以下操作:

uint32_t a = 0x1234568;
a = reinterpret_cast<uint32_t>(-a);

因为 reinterpret_cast 做了我想要的,这意味着直接解释字节而不需要任何类型的转换/转换。

  • 为此目的我需要 reinterpret_cast 吗?
  • 这是否违反了严格的别名?
  • 如果我做错了,最好的实现方式是什么?

我问这个问题是因为虽然代码显然在 gcc 下工作,但它在 Visual Studio 下不起作用(无法从 uint32_t 转换为 uint32_t应用于无符号的一元减号运算符类型,结果仍未签名)。这些错误是有道理的,但我不确定除了使用 bit hack 计算 2 的互补值之外,我该如何以不同的方式做到这一点。

最佳答案

  • 这里不需要reinterpret_caststatic_cast就足够了。
  • 您的代码不适用于指针,因此不存在别名问题。
  • 结论:这种方法没有任何问题。

顺便说一句:您的代码确实编译为“neg”指令,至少在 Intel 平台上是这样。 ;-)


更新:

C++ 语言规范说:

The operand of the unary − operator shall have arithmetic or enumeration type and the result is the negation of its operand. Integral promotion is performed on integral or enumeration operands. The negative of an unsigned quantity is computed by subtracting its value from 2 n, where n is the number of bits in the promoted operand. The type of the result is the type of the promoted operand.

并且由于无符号类型被提升为自身,一元减号可以应用于无符号类型并且不会更改它们。

所以这样写是正确的,例如:

uint32_t convert( uint32_t x ) {
return -x;
}

static_cast 可以在那里使用,但不是必需的。 reinterpret_cast 不能用于转换整数。

关于c++ - 类型安全和 NEG 指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30802457/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com