开发者

Encoding is not giving the right result in objective c

开发者 https://www.devze.com 2023-04-07 20:35 出处:网络
I have a c# code which encodes a string. I am trying to write a corresponding routine in objective c.

I have a c# code which encodes a string. I am trying to write a corresponding routine in objective c.

The code is as follows:

    // c# code
public static string Encode(Guid guid)
{
  string encode = convert.ToBase64String(guid.ToByteArray());
  encode = encoded.Replace("/","_").Replace("+","-");
  return encoded.substring(0,22);
}

I have written this code in objective c.

- (NSString *)encode:(NSString *)inId
{
NSString *uniqueId = inId;

// convert user id in to data
NSData *userIdData = [uniqueId dataUsingEncoding:NSUTF16StringEncoding];
// convert encoded userId's data into base64EncodedString
NSString *base64String = [Base64 encode:userIdData];
//NSString *base64String = [userIdData encodeBase64ForData];

NSString *encodedId = [[NSString alloc] initWithString:base64String];
// replace "/" character in base64String into "_" character
encodedId = [encodedId stringByReplacingOccurrencesOfString:@"/" withString:@"_"];
// replace "+" character in base64String into "-" character
encodedId = [encodedId stringByReplacingOccurrencesOfString:@"+" withString:@"-"];
// get substring of range 22
encodedId = [encodedId substringToIndex:22];
NSLog(@"Base 64 encoded = %@",encodedId); 
 return encodedId;
}

I am calling this function from viewDidLoad

开发者_JS百科
NSString *encodedStr = [self encode:@"a8f9f344-d14e-4541-a8e7-0f5936e42254"];// string to encode
NSLog(@"Encoded String %@",encodedStr);

this code is not giving me the correct result i want for eg:for the string a8f9f344-d14e-4541-a8e7-0f5936e42254 it should give result as RPP5qE7RQUWo5w9ZNuQiVA.

Thanks.


Your problem is that guid.ToByteArray() and [uniqueId dataUsingEncoding:NSUTF16StringEncoding]; do not do the same thing. As far as I can tell from the documentation, the former removes the hyphens and treats the rest as the hex ASCII representation of 16 bytes. The latter just turns each character into UTF16 (actually, it is UTF-16 already) and puts it into an NSData.

You need to write some code in Objective-C to take an ASCII Hex string and convert it into bytes.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号