简体   繁体   English

Objective-C中的二进制转换算法

[英]Binary conversion algorithm in objective-c

How do I get the value of a certain bit from a byte or integer? 如何从字节或整数中获取某个位的值? The only similar answer that I've been able to find is for a specific character inside a string. 我能够找到的唯一类似答案是针对字符串中的特定字符。 I am trying to convert a binary number to a decimal number, and perhaps there is a much simpler way to do this, but I was thinking of this: multiplying 2^(position of integer from right) by either a 1 or 0, depending on the value of the integer at the position previously mentioned. 我正在尝试将二进制数转换为十进制数,也许有一种更简单的方法可以执行此操作,但是我在想:将2 ^(整数从右开始的位置)乘以1或0,具体取决于在前面提到的位置的整数值上。 Any tips? 有小费吗?

NSString * binary = @"0011010";
long value = strtol([b UTF8String], NULL, 2);

There are multiways of obtaining the value of bit within a byte or integer. 获取字节或整数内的位的值有多种方法。 It all depends on your needs. 这完全取决于您的需求。

One way would be to use a mask with bitwise operators. 一种方法是将掩码与按位运算符一起使用。

int result = sourceValue & 8;    // 8 ->  0x00001000
// result non zero if the 4th bit from the right is ON.

You can also shift bits one by one and read, say, the right-most bit. 您也可以一位一位地移位,然后读取最右边的一位。

for (int i = 0;  i < 8; i++)
    NSLog(@"Bit %d is %@", i, (sourceValue % 2 == 0) ? @"OFF" : @"ON");
    sourceValue = sourceValue >> 1;  // shift bits to the right for next loop.
}

Or if you just want the text representation for an integer, you could let NSNumber do the work: 或者,如果您只想要整数的文本表示形式,则可以让NSNumber进行工作:

NSString* myString = [[NSNumber numberWithInt:sourceValue] stringValue];

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

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