将 2 个字符转换为 1 个整数 [英] Convert 2 char into 1 int

查看:25
本文介绍了将 2 个字符转换为 1 个整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 2 个字符:HIGH 和 LOW,我想将它们转换为对应于 HIGH + LOW 的 2 个左位的 int.

I have 2 chars: HIGH and LOW and I'd like to convert them to an int corresponding to HIGH + the 2 left bits from LOW.

我试过类似的东西:

unsigned char high;
unsigned char low;
high = 128; // 10000000
low= 128; // 10000000
int result; (should be high 10000000 + 2 left bites of low 10 = 1000000010)
// To do
return result;

为更清晰而编辑.

我选择的解决方案是:

return high*4 + (low >> (CHAR_BIT - 2));

推荐答案

你声明 HIGHLOWchar*,但你没有不要将它们用作指针.以下代码可以正常工作(顺便说一句,不使用常量时避免使用大写标识符):

You declare HIGH and LOW as char*, but you don't use them as pointer. The following code works fine (BTW, avoid upper case identifiers when you don't use constants):

char high = 125;
char low = 12;

我是这样理解你的问题的(可能更容易理解):

This is how I understand your question (it could be more understandable):

#include <limits.h>

int result = high + (low >> (CHAR_BIT - 2));

这篇关于将 2 个字符转换为 1 个整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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