Forum Xamarin Xamarin.iOS

initWithBytes and Length problem

Hi,

I am trying to get data from an NSData. I have been changing an obj-C code into c# on Xamarin.ios and have been successful, so far.

I had a question here before and was answered, so I was hoping I could get some help again.

Obj-C

    const uint8_t *bytes=(uint8_t *)[data bytes];

    int Len=bytes[index++];

    NSString *maskedData=[[NSString alloc] initWithBytes:&bytes[index] length:Len encoding:NSASCIIStringEncoding];

    NSLog(@"Masked Data: %@", maskedData);

Xamarin.iOS

    byte[] bytes = data.ToArray();

    //adding index to get to the right starting point
    int Len = Buffer.GetByte(bytes, index++);

    NSData.FromArray(bytes);
    NSData dataFromByte = NSData.FromStream(new MemoryStream(bytes));
    Console.WriteLine($"{dataFromByte.ToString().Substring(index, Len)}");

    //I want to use this, but there is no Length option on Xamarin.iOS to specify until where to read
    //so using it just sends the whole data to it
    NSString maskedData = new NSString(dataFromByte, NSStringEncoding.ASCIIStringEncoding);

    //hence I am using this instead and convert the hex to string
    string maskedHex = dataFromByte.ToString().Substring(index, Len);

When using NSLog and Console.WriteLine, I get the same index and Len throughout the same data.

The data is being sent as NSData. I got the way to copy iniWithBytes from this link:

https://forums.xamarin.com/discussion/11254/equivalent-of-initwithbytes-of-nsdata-class

But the string I receive when logging is different when passing through. I get the same data from start, but it is cut less than halfway through, thus getting less data when reading through Xamarin.iOS. Am I doing something wrong or is there something different when reading bytes with c#? Or is it because I am using substring instead and converting it to string that makes it change?

Any help would be appreciated. Thank you.

Best Answer

  • 9lorenz299lorenz29 Member ✭✭
    Accepted Answer

    Nevermind, I got it to work using

    NSData dataFromByte = NSData.FromStream(new MemoryStream(bytes,index, Len));

Answers

  • 9lorenz299lorenz29 Member ✭✭
    Accepted Answer

    Nevermind, I got it to work using

    NSData dataFromByte = NSData.FromStream(new MemoryStream(bytes,index, Len));

Sign In or Register to comment.