【问题标题】:Convert NSString to 4 by 4 float Matrix将 NSString 转换为 4 x 4 浮点矩阵
【发布时间】:2012-01-20 09:09:48
【问题描述】:

我想知道是否有一种方便的方法或其他方法可以将 NSString 更改为浮点数组。

我有一个这样的字符串:

{{-0.528196, -0.567599, -0.631538, 0}, {0.0786662, -0.773265, 0.629184, 0}, {-0.845471, 0.282651, 0.453086, 0}, {0, 0, 0, 1}}

我通过方法得到的:

NSStringFromGLKMatrix4()

我想这样做:

float test[4][4] = {{-0.528196, -0.567599, -0.631538, 0}, {0.0786662, -0.773265, 0.629184, 0}, {-0.845471, 0.282651, 0.453086, 0}, {0, 0, 0, 1}};

return GLKMatrix4MakeWithArray(*test);

任何帮助将不胜感激,谢谢。

【问题讨论】:

    标签: objective-c ios5 xcode4.2


    【解决方案1】:

    这有点难看,但应该可以:

    // your string data
    NSString* s = @"{{-0.528196, -0.567599, -0.631538, 0}, {0.0786662, -0.773265, 0.629184, 0}, {-0.845471, 0.282651, 0.453086, 0}, {0, 0, 0, 1}}";
    
    // remove uneccessary characters from string.. 
    s = [s stringByReplacingOccurrencesOfString:@"{" withString:@""];
    s = [s stringByReplacingOccurrencesOfString:@"}" withString:@""];
    s = [s stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    // build an NSArray with string components and convert them to an array of floats
    NSArray* array = [s componentsSeparatedByString:@","];
    float data[16];
    for(int i = 0; i < 16; ++i){
        data[i] = [[array objectAtIndex:i] floatValue];
    }
    
    GLKMatrix4 matrix = GLKMatrix4MakeWithArray(data);
    

    如果您的目标是 iOS 4.0 或更高版本,您还可以使用 NSRegularExpression 从字符串中取出数字。

    【讨论】:

    • 谢谢,请注意,我认为“withstring”有错字,因为我假设您想删除所有这些符号,所以它应该是“”。
    【解决方案2】:

    显然,好的 ole Ansi C... sscanf ... 早已失传和遗忘。

    sscanf(...,"{{%f,%f,%f,%f}, ...",...);
    

    您可以在hexString 帖子中查看我的 sscanf 代码作为附加示例。

    【讨论】:

    • 是不是像 sscanf(string,"{{%f,%f,%f,%f},{%f,%f,%f,%f},{%f, %f,%f,%f},{%f,%f,%f,%f}}",数据[0],数据[1],数据[2],数据[3],数据[4] ,数据[5],数据[6],数据[7],数据[8],数据[9],数据[10],数据[11],数据[12],数据[13],数据[14] ,数据[15]); ??
    • 是的……这实际上是正确的。确保您的变量是通过指针传递的,并且您可以检查返回变量以查看是否已解析所有元素...即 16。您还可以在 '%' 和 'f' 说明符之间添加不同的参数来更改解析。有关格式化的详细信息,请参见 printf 手册页。
    【解决方案3】:

    使用NSStringcomponentsSeparatedByString:方法检索数组中的值,然后使用 GLKMatrix4MakeWithArray 方法。

    【讨论】:

      【解决方案4】:

      使用 NSValue,这是 Apple 提供的用于 C 类型结构和 Objective-C 对象之间转换的更好选择。

      编码

      GLKMatrix4 encMatrix = /* your matrix */;
      NSValue *encMatrixValue = [NSValue value:&encMatrix withObjCType:@encode(GLKMatrix4)];
      

      解码

      GLKMatrix4 decMatrix;
      [encMatrixValue getValue:&decMatrix];
      

      这比将 GLKMatrix 转换为 NSString 再转换回 GLKMatrix 更干净和稳定。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-05-14
        • 2012-06-11
        • 2011-06-08
        • 1970-01-01
        • 2022-01-04
        • 1970-01-01
        • 2019-01-21
        • 2014-08-13
        相关资源
        最近更新 更多