【问题标题】:How do I convert int to int8_t?如何将 int 转换为 int8_t?
【发布时间】:2014-07-08 04:03:32
【问题描述】:

如何将int 转换为int8_t? cast() / to!int8_t() 不起作用。

const nblocks = l /4;
const int8_t i = to!int8_t(nblocks) * 4;

编译错误:

错误:不能隐式转换表达式 (cast(int)to(nblocks) * 4) int 到 const(byte) 的类型

【问题讨论】:

    标签: casting type-conversion d dmd


    【解决方案1】:

    int8_t 是 C/C++ 中 signed char 的 typedef(8 位,有符号整数)。这种类型对应于 D 中的byte,所以to!byte(nblocks) 应该可以工作。

    【讨论】:

      【解决方案2】:

      如果你想使用 C 的 stdint,Phobos 中的模块 std.stdint 提供了正确的别名。

      文档:http://dlang.org/phobos/std_stdint.html

      编辑:代码中的原始问题是最后一行中的四乘法。当您将 byte/int8_t 乘以四时,该值可能不适合一个字节。如果您确定要以字节为单位,那么您可以使用已检查的转换为byte/int8_t,使用to 作为总结果,或者使用未检查的cast

      const int8_t i = (nblocks * 4).to!int8_t;
      

      【讨论】:

      • 这是我正在使用并导致错误的那个。我并不是在寻找 C 的那种,而是一种具有相同大小的数据类型。所以我发现了。
      • 当我重读我的答案时,我意识到我没有回答你的问题。我已经更新了我的答案,解释了你的例子出了什么问题。所以byteint8_t 应该有同样的问题。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-05-22
      • 1970-01-01
      • 1970-01-01
      • 2020-07-17
      • 2013-04-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多