Hi I want to convert the NSString into Byte array.
if I have string like "Hello" then it convert into byte like this {65,23,56,56,56}.
thanks
An NSString object can be initialized from or written to a C buffer, an NSData object, or the contents of an NSURL . It can also be encoded and decoded to and from ASCII, UTF–8, UTF–16, UTF–32, or any other string encoding represented by NSStringEncoding .
In Swift a byte is called a UInt8—an unsigned 8 bit integer. A byte array is a UInt8 array. In ASCII we can treat chars as UInt8 values. With the utf8 String property, we get a UTF8View collection. We can convert this to a byte array.
NSString : Creates objects that resides in heap and always passed by reference. String: Its a value type whenever we pass it , its passed by value. like Struct and Enum, String itself a Struct in Swift.
Use -[NSString UTF8String]
which returns const char*
. Read the reference.
A general tip: if you want to find if a class has a method which does something, look up the official reference! I mean, on the web, there's not only Stack Overflow, but the API provider's (i.e. Apple's or Microsoft's) official documentations!
NSData *bytes = [test dataUsingEncoding:NSUTF8StringEncoding];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With