0

I have a NSString which i have to convert into NSData. After converting into NSData, I need to transpose the NSData in objective-c. How do i transpose NSData in objective -c ?

Thanks

sia
  • 1,872
  • 1
  • 23
  • 54
  • Possible duplicate of [How do I convert an NSString value to NSData?](https://stackoverflow.com/questions/901357/how-do-i-convert-an-nsstring-value-to-nsdata) – MD. Dec 06 '17 at 08:42
  • What does transposing NSData in Objective-C mean? – El Tomato Dec 06 '17 at 10:34
  • You appear to be using "transpose" in an unfamiliar way. Taken literally a transposition of an ordered set of bytes would just exchange two bytes in the sequence; I doubt this is what you mean. Are you converting the string to, say, UTF-16 byte pairs and which to change the endian order by transposing each pair of bytes? Or do you wish to reverse the order of all the bytes? People need more detail to help you. Editing the question and adding the code you have and saying what you've tried/exactly where you get stuck would help people to help you. HTH – CRD Dec 06 '17 at 21:03
  • @CRD - need to reverse the order of all bytes – sia Dec 07 '17 at 02:47

1 Answers1

1

It seems you wish to reverse the order of the bytes, here is an outline algorithm:

  1. Use NSData's length to get the number of bytes
  2. Allocate a C-array of type Byte to hold the bytes. Use one of the malloc() family.
  3. Use getBytes:length: to get a copy of the bytes
  4. Set a C Byte * variable, say frontPtr, to point at the first byte; set another, say rearPtr to point at the last byte.
  5. Now iterate, exchanging the bytes referenced by the two pointers, then increment frontPtr, decrement rearPtr, and keep iterating while rearPtr > frontPtr.
  6. Create a new NSData from the working buffer using NSData's + dataWithBytesNoCopy:length:freeWhenDone: passing YES as the last argument - this will take ownership of the malloc'ed buffer so there is no need for you to free it.

The algorithm simply moves two pointers from the ends of the buffer towards the middle exchanging bytes as it goes. The termination condition make it work for even and odd lengths (in the latter case the middle byte doesn't need to be swapped).

If one the other hand you didn't wish to reverse the order of the bytes, but instead reverse the order of bits in each byte Google "C bit reverse" and follow the same general structure as the above algorithm but do bit reversing in the loop.

If after coding the above you have a problem ask a new question, include your code, and explain your issue. Someone will undoubtedly help you.

HTH

CRD
  • 52,522
  • 5
  • 70
  • 86