Reputation: 301
I'm making a project on Windows and iOS.
In windows, I take input from user, convert it to byte array, manipulate the array by adding large random values to every byte (kind of like encoding it), then give the byte array converted to String back to the user.
I want to implement the same thing in an iOS app. I take input from a UITextField (outlet say: myTextField)
Now the thing is, how do I convert it to a byte array as in Windows and manipulate it. I searched stack overflow and found this piece of code
const char *bytearray = [self.myTextField.text UTF8String];
Using this, it gave me a byte array as I desired, but its a const char *, and I cannot manipulate it. So how do I store it in an array to manipulate it.
Also, when adding values to bytes in array in windows, if the value goes beyond 256, it stays within 256 automatically (say, 115 + 300, it is stored as 159), this eases my process of subtracting the value and getting the original value back. How can this be done in the iOS app.
For a better clarity, I'll give an example of how it works in Windows
byte array contains 'n' (Decimal value: 110)
adding 200 to it stores '6' (Decimal value: 54)
[310 % 256 = 54]
When retrieving back original value I subtract 200 from '6' (54 - 200 = -146)
and get the original value (256 - 146 = 110)
All this is done automatically, by using a byte array (this 256 - 146 thing)
How do I achieve this byte array capability in iOS?
Upvotes: 0
Views: 1194
Reputation: 124997
how do I convert it to a byte array as in Windows and manipulate it. I searched stack overflow and found this piece of code
Take a look at NSString's -getCString:maxLength:encoding:
method, which will interpret the string using the encoding you specify and copy the result into the buffer you provide. You can then manipulate it however you like. There are one or two other methods along similar lines, but that one should get you started.
To convert back to a NSString, you can use +stringWithCString:encoding
, +stringWithUTF8String:
, +stringWithCharacters:length:
, or the -init...
versions of any of those.
Also, when adding values to bytes in array in windows, if the value goes beyond 256, it stays within 256 automatically (say, 115 + 300, it is stored as 159), this eases my process of subtracting the value and getting the original value back. How can this be done in the iOS app.
It's not the operating system that determines that sort of behavior, but the language. Objective-C's behavior on this respect is just like that of C, C++, and probably C# -- if you're working with a type like unsigned char
, values will be constrained to 0..255. After all, you can only fit so many values in 8 bits.
Upvotes: 1
Reputation: 3038
I would convert the NSString object into an NSMutableData object. Then with [NSMutableData mutableBytes] you get the array you want to manipulate.
Upvotes: 1