如何将带有十六进制数据的char(或Byte)转换为整数(十进制值)

时间:2022-10-15 17:08:35

I have

我有

char tem;

Its value is shown as blow:

它的价值显示为打击:

Printing description of tem:
(char) tem = '\xd1'

which should equals to 209 in decimal.

其应该等于209的十进制数。

My question is how can I implement this conversion programmatically? That is I want to get a NSInteger that equals 209 in this case.

我的问题是如何以编程方式实现此转换?那就是我希望在这种情况下得到一个等于209的NSInteger。

3 个解决方案

#1


0  

Maybe there’s something I’m overlooking here, but given that both char and NSInteger are integral types, can’t you just do

也许我在这里有一些东西,但鉴于char和NSInteger都是不可或缺的类型,你不能只做

char tem = '\xd1';
NSInteger i = tem;

? Or perhaps, to avoid surprises from sign extension,

?或者,为了避免签名扩展的意外,

NSInteger i = tem & 0xff;

#2


0  

A char variable actually is a 8-bit integer. You don't have to convert it to a NSInteger to get its decimal value. Just explicitly tell the compiler to interpret it as an unsigned 8-bit integer, uint8_t:

char变量实际上是一个8位整数。您不必将其转换为NSInteger以获取其十进制值。只需明确告诉编译器将其解释为无符号的8位整数uint8_t:

char theChar = '\xd1';
NSLog(@"decimal: %d", (uint8_t)theChar);    //prints 'decimal: 209'

To convert it to a NSInteger:

要将其转换为NSInteger:

NSInteger decimal = (uint8_t)theChar;

#3


0  

If yours char in ANSCII, do this:

如果您在ANSCII中使用char,请执行以下操作:

char a = '3';//example char
int i = (int)(a - '0');

#1


0  

Maybe there’s something I’m overlooking here, but given that both char and NSInteger are integral types, can’t you just do

也许我在这里有一些东西,但鉴于char和NSInteger都是不可或缺的类型,你不能只做

char tem = '\xd1';
NSInteger i = tem;

? Or perhaps, to avoid surprises from sign extension,

?或者,为了避免签名扩展的意外,

NSInteger i = tem & 0xff;

#2


0  

A char variable actually is a 8-bit integer. You don't have to convert it to a NSInteger to get its decimal value. Just explicitly tell the compiler to interpret it as an unsigned 8-bit integer, uint8_t:

char变量实际上是一个8位整数。您不必将其转换为NSInteger以获取其十进制值。只需明确告诉编译器将其解释为无符号的8位整数uint8_t:

char theChar = '\xd1';
NSLog(@"decimal: %d", (uint8_t)theChar);    //prints 'decimal: 209'

To convert it to a NSInteger:

要将其转换为NSInteger:

NSInteger decimal = (uint8_t)theChar;

#3


0  

If yours char in ANSCII, do this:

如果您在ANSCII中使用char,请执行以下操作:

char a = '3';//example char
int i = (int)(a - '0');