美文网首页
进制转换

进制转换

作者: SMFly | 来源:发表于2016-07-17 17:53 被阅读27次

    //反转字符串

    + (NSString*)fanZhuan:(NSString*)str{

    unsignedlonglen;

    len = [strlength];

    unichara[len];

    for(inti =0; i < len; i++)

    {

    unicharc = [strcharacterAtIndex:len-i-1];

    a[i] = c;

    }

    return[NSStringstringWithCharacters:alength:len];

    }

    //十进制转二进制

    + (NSString*)toBinarySystemWithDecimalSystem:(NSString*)decimal With:(int)length

    {

    NSString* temStr =@"";

    NSString* result =@"";

    intnum = [decimalintValue];

    intremainder =0;//余数

    intdivisor =0;//除数

    while(true)

    {

    remainder = num%2;

    divisor = num/2;

    num = divisor;

    temStr = [temStrstringByAppendingFormat:@"%d",remainder];

    if(divisor ==0)

    {

    break;

    }

    }

    for(inti = (int)(temStr.length-1); i >=0; i --)

    {

    result = [resultstringByAppendingFormat:@"%@",

    [temStrsubstringWithRange:NSMakeRange(i ,1)]];

    }

    if(result.length<= length)

    {

    NSMutableString*b = [[NSMutableStringalloc]init];;

    for(inti =0; i < length - result.length; i++)

    {

    [bappendString:@"0"];

    }

    return[selffanZhuan:[bstringByAppendingString:result]];

    }

    else

    {

    return[selffanZhuan:result];

    }

    }

    //二进制转十进制

    + (NSString*)toDecimalSystemWithBinarySystem:(NSString*)binary

    {

    NSString* temStr = [selffanZhuan:binary];

    intll =0;

    inttemp =0;

    for(inti =0; i < temStr.length; i ++)

    {

    temp = [[temStrsubstringWithRange:NSMakeRange(i,1)]intValue];

    temp = temp *powf(2, temStr.length- i -1);

    ll += temp;

    }

    NSString* result = [NSStringstringWithFormat:@"%d",ll];

    returnresult;

    }

    相关文章

      网友评论

          本文标题:进制转换

          本文链接:https://www.haomeiwen.com/subject/hgfpjttx.html