将uint16_t解释为int16_t [英] Interpreting a uint16_t as a int16_t

查看:1092
本文介绍了将uint16_t解释为int16_t的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个可移植的和安全的方法来解释由 boost :: uint16_t 作为 boost :: int16_t ?我有一个 uint16_t ,我知道代表一个有符号的16位整数编码为小端。我需要对这个值进行一些有符号的算术,那么有没有说服编译器它已经是一个有符号的值?



如果我没有错误,

解决方案

code> static_cast 会转换该值,

如果你正在寻找一个不同于cast的东西,那么将它的内存表示复制到 boost :: int16_t ,因为它代表了它的开头。 / p>

编辑:如果您必须在大端机上工作,只需将字节向后复制。使用 std :: copy std :: reverse


Is there a portable and safe way to interpret the bit-pattern made by a boost::uint16_t as a boost::int16_t? I have a uint16_t, which I know represents a signed 16-bit integer encoded as little-endian. I need to do some signed arithmetic on this value, so is there anyway to convince the compiler that it already is a signed value?

If I a not mistaken, a static_cast<int16_t> would convert the value, perhaps changing its bit-pattern.

解决方案

If you are looking for something different than a cast, then copy its memory representation to that of a boost::int16_t since its what it represents to begin with.

Edit: If you have to make it work on a big endian machine, simply copy the bytes backwards. Use std::copy and std::reverse.

这篇关于将uint16_t解释为int16_t的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆