gpt4 book ai didi

objective-c - 将十进制转换为二进制(字符的位图)

转载 作者:行者123 更新时间:2023-12-01 17:33:38 25 4
gpt4 key购买 nike

我有一个关于从字符(例如A)获取位图的问题。

我已经在互联网上搜索,但没有直接帮助。我找到了this页面,其中描述了我的计划。

来自本网站的报价:

例如字符char =“A” bits =“227873781661662”转换为二进制形式的“0000 0000 0000 0000 1100 1111 0011 1111 1111 1111 1100 1111 0011 1111 1101 1110”。

它们如何从227873781661662变为0000 0000 0000 0000 1100 1111 0011 1111 1111 1111 1100 1111 0011 1111 1101 1110?

int num = 227873781661662;
int n = log(num)/log(2)+1;          //Figure out the maximum power of 2 needed
NSString *result = @"";             //Empty string
for (int j=n; j>=0; j--)            //Iterate down through the powers of 2
{
if (pow(2,j) >= num)            //If the number is greater than current power of 2
{
num -= pow(2,j);                             //Subtract the power of 2
result = [result stringByAppendingString:@"1"]; //Add a 1 to result string
}
else result = [result stringByAppendingString:@"0"]; //Otherwise add a 0

if (num == 0) break;                              //If we're at 0, stop
}
NSLog(@"num = %i",num);

这有什么问题?感谢帮助

最佳答案

要将数字从十进制转换为二进制:

long long num = 938409238409283409;
int n = log(num)/log(2)+1; //Figure out the maximum power of 2 needed
NSString *result = @""; //Start with empty string
for (int j=n; j>=0; j--) //Iterate down through the powers of 2
{
long long curPOW = powl(2,j);
if (curPOW <= num) //If the number is greater than current power of 2
{
num -= curPOW; //Subtract the power of 2
result = [result stringByAppendingString:@"1"]; //Add a 1 to result string
}
else result = [result stringByAppendingString:@"0"]; //Otherwise add a 0
}
NSLog(@"%@", result); //Result is now binary representation of num

在上面的 num示例中,输出为:

关于objective-c - 将十进制转换为二进制(字符的位图),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11797460/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com