在C ++中将char转换为int而无符号位传播 [英] Converting char to int without sign bit propagation in C++

查看:50
本文介绍了在C ++中将char转换为int而无符号位传播的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个字节的数据存储在'char'成员变量中.它可能应该存储为"unsigned char",但是不能更改.我需要通过一个'int'变量来检索它,但不要传播符号位.

A byte of data is being stored in a 'char' member variable. It should probably be stored as an 'unsigned char' instead, but that can't be changed. I need to retrieve it through an 'int' variable, but without propagating the sign bit.

我的解决方法是这样(UINT和UCHAR是显而易见的类型):

My solution was this (UINT and UCHAR are the obvious types):

void Foo::get_data( int *val )
{
    if( val )
        *val = (int)(UINT)(UCHAR)m_data;  // 'm_data' is type 'char'
}

这对我来说似乎是最好的解决方案.我可以用

This seemed the best solution to me. I could use

*val = 0xff & (int)m_data;

而不是强制类型转换,但这似乎不可读.哪种方法更好(如果有),为什么?

instead of the casting, but this doesn't seem as readable. Which alternative is better, if either, and why?

推荐答案

只需编写

*val = (UCHAR)m_data;

现在,表达式(UCHAR)m_data 具有无符号类型,不会传播任何符号位.

As now the expression (UCHAR)m_data has an unsigned type neither sign bit will be propagated.

这篇关于在C ++中将char转换为int而无符号位传播的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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