how to convert array of bytes to base64 String in iphone?

Viewed 10795

I have a piece of code in vb. I need to convert array of bytes to base 64 string. Following is the vb code.

If arrLicence.Count > 0 Then

LicenceBytes = CType(Array.CreateInstance(GetType(Byte),6), Byte())

        LicenceBytes(0) = Convert.ToByte(arrLicence(0).ToString(), 16)
        LicenceBytes(1) = Convert.ToByte(arrLicence(1).ToString(), 16)
        LicenceBytes(2) = Convert.ToByte(arrLicence(2).ToString(), 16) 
        LicenceBytes(3) = Convert.ToByte(arrLicence(3).ToString(), 16) 
        LicenceBytes(4) = Convert.ToByte(arrLicence(4).ToString(), 16)
        LicenceBytes(5) = Convert.ToByte(arrLicence(5).ToString(), 16)

        LicenceString = Convert.ToBase64String(LicenceBytes) '6 byteArray - passed by the user - Base64Encoded

I need its equivalent in iphone. I tried with NSData and base64 conversion but result defers.

I have used this link for conversion. http://www.cocoadev.com/index.pl?BaseSixtyFour

I tried by creating individual bytes using memcpy and then creating an array but with no success.

What I have tried is as follows:

NSData *d1 =[@"64" dataUsingEncoding:NSUTF16StringEncoding];
NSData *d2 = [@"37" dataUsingEncoding:NSUTF16StringEncoding];
NSData *d3 = [@"81" dataUsingEncoding:NSUTF16StringEncoding];
NSData *d4 = [@"d4" dataUsingEncoding:NSUTF16StringEncoding];

unsigned char *buffer = (unsigned char*)malloc(8);
buffer[0] =  [d1 bytes]  ;
buffer[1] =  [d2 bytes] ;
buffer[2] =  [d3 bytes] ;
buffer[3] =  [d4 bytes] ;

NSData *data = [NSData dataWithBytes:buffer length:4];

NSString *str = [self encodeBase64WithData:data];
free(buffer);

This results in IJCgkA== while code in .NET returns ZDeB1A==

Please note that the conversion is for first four bytes of arrLicence and the input is 64, 37, 81, d4

6 Answers
Related