简体   繁体   English

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

[英]How to convert char(or Byte) with hexadecimal data in it, to an integer(decimal value)

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。

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;

A char variable actually is a 8-bit integer. 一个char变量实际上一个8位整数。 You don't have to convert it to a NSInteger to get its decimal value. 您不必将其转换为NSInteger即可获取其十进制值。 Just explicitly tell the compiler to interpret it as an unsigned 8-bit integer, uint8_t : 只需明确告诉编译器将其解释为无符号的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;

If yours char in ANSCII, do this: 如果您是ANSCII中的角色,请执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM