Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 724
DivineDesert Avatar asked Jun 24 '11 09:06

DivineDesert


2 Answers

Try this one, i hope this will surely help you. get-base64-nsstring-from-nsdata

like image 191
Mobile Developer iOS Android Avatar answered Oct 25 '22 11:10

Mobile Developer iOS Android


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

Not sure what you expect this to do. bytes return an array, and you are assigning the addresses of the arrays to char elements of your buffer. This buffer won't be filled with any of the data you expect, and the "data" from d2 will partially overwrite those from d1 etc.

Also, you shouldn't make much assumptions about the lengths of your byte arrays, especially not if using UTF-16.

In a word: You don't throw the data you expect at your conversion routine. Maybe check that in the debugger.

like image 26
Eiko Avatar answered Oct 25 '22 09:10

Eiko