Convert string to only byte in Objective-C - ios

I have a problem, want to convert a decimal byte to a hexadecimal byte, pass it to string to be able to make the conversion more quickly but now my question is as follows. Know how can I convert a string to a byte the string
example:
NSString *var = #"0x21";
To
Byte cmd = 0x21;

You can convert an instance of NSString to an instance of NSData with -dataUsingEncoding:allowLossyConversion: or to a C array with -getCString:maxLength:encoding:(NSStringEncoding)encoding.
In both cases you have a pointer to an object resp. to a char[]. Putting that pointer into the Byte array, will convert the pointer and copy its value, but not the referenced data.
Additionally: In your example you try to save 0.4 (zero – period – four) and 0.5 (zero – period – 5) into a Byte[]. This will not do the job, you probably expect. It will convert the value to a value of type Byte (an integer type!) and store that value. Integer values greater than 255 will be converted, too.
Therefore you have to use a mutable data object and concat the binary representation of the different types individually.

Related

What type is NSString and how many bytes?

I am new to objective c. Trying to find out the type of NSString in Objective C. I use the sizeof() method from C and lengthOfBytesUsingEncoding method using UTF8 encoding from NSString.
NSString *test=#"a";
NSLog(#"LengthOfBytesUsingEncoding: %lu bytes", [test lengthOfBytesUsingEncoding:NSUTF8StringEncoding]);
printf("NSString: %lu\n", sizeof(test));
This is gonna give me in Console
LengthOfBytesUsingEncoding: 1 bytes
and NSString: 8 bytes
What is the difference between the two results?
Why LengthOfBytesUsingEncoding returns 1 bytes and sizeof method returns 8 bytes?
What is the type of NSString? Int, float, long, long double?
The length of bytes gives you the length of text content using the specified encoding. In this case the string contains a single character, which in UTF8 is encoded as 1 byte.
The sizeof gives you the size of the variable's type, which, in this case is a pointer to NSString. The size of all pointers on 64bit architectures is 8 bytes. It's essentially the size of memory address, where NSString data is stored. sizeof is not a method and it's not even a function. It's an operator. The result is known at compile-time.
In other words:
The actual string contents are stored in memory in a format that is opaque and shouldn't interest you.
On another place in memory, there is NSString data structure that contains a pointer to the contents. You can get the size of this structure using sizeof(NSString) (actually the size will differ depending on concrete NSString subclass, e.g. NSMutableString, NSPlaceholderString etc).
Your variable contains a pointer to NSString, that is, its size is sizeof(NSString*), which is always 8 bytes.
sizeof operator shouldn't interest you much in Objective-C, unless you are dealing with pointer arithmetics, which should be rather rare.

Preparing data in TLV8

I'm writing a HomeKit (so perhaps Bluetooth) characteristic in TLV8 format. Apple doc says
The value is an NSData object containing a set of one or more TLV8's,
which are packed type-length-value items with an 8-bit type, 8-bit
length, and N-byte value.
According to Wikipeida a type-length value is
Type
A binary code, often simply alphanumeric, which indicates the kind of field that this part of the message represents;
Length
The size of the value field (typically in bytes);
Value
Variable-sized series of bytes which contains data for this part of the message.
I have no idea how to pack one. I suppose I can write raw bytes to NSData, but what do I write for pad, if I need any padding, etc. So is there an example of how to do that?
Oh I figured it out.
TLV8 consist of three sections: "Tag", "Length", and "Value". I don't know what 8 means.
Both tag and length are UInt8. I believe what the tag may be depend on where the TLV8 is used. Length is the length of the value. Value is the content it self.
So when I want to send a simple 1 as a value, I use:
let tag = 0x02 // For example
let length = 0x01
let value = 0x01
let data = Data(bytes: [tag, length, value]) // NSData

Convert first two bytes of Lua string (in bigendian format) to unsigned short number

I want to have a lua function that takes a string argument. String has N+2 bytes of data. First two bytes has length in bigendian format, and rest N bytes contain data.
Say data is "abcd" So the string is 0x00 0x04 a b c d
In Lua function this string is an input argument to me.
How can I calculate length optimal way.
So far I have tried below code
function calculate_length(s)
len = string.len(s)
if(len >= 2) then
first_byte = s:byte(1);
second_byte = s:byte(2);
//len = ((first_byte & 0xFF) << 8) or (second_byte & 0xFF)
len = second_byte
else
len = 0
end
return len
end
See the commented line (how I would have done in C).
In Lua how do I achieve the commented line.
The number of data bytes in your string s is #s-2 (assuming even a string with no data has a length of two bytes, each with a value of 0). If you really need to use those header bytes, you could compute:
len = first_byte * 256 + second_byte
When it comes to strings in Lua, a byte is a byte as this excerpt about strings from the Reference Manual makes clear:
The type string represents immutable sequences of bytes. Lua is 8-bit clean: strings can contain any 8-bit value, including embedded zeros ('\0'). Lua is also encoding-agnostic; it makes no assumptions about the contents of a string.
This is important if using the string.* library:
The string library assumes one-byte character encodings.
If the internal representation in Lua of your number is important, the following excerpt from the Lua Reference Manual may be of interest:
The type number uses two internal representations, or two subtypes, one called integer and the other called float. Lua has explicit rules about when each representation is used, but it also converts between them automatically as needed.... Therefore, the programmer may choose to mostly ignore the difference between integers and floats or to assume complete control over the representation of each number. Standard Lua uses 64-bit integers and double-precision (64-bit) floats, but you can also compile Lua so that it uses 32-bit integers and/or single-precision (32-bit) floats.
In other words, the 2 byte "unsigned short" C data type does not exist in Lua. Integers are stored using the "long long" type (8 byte signed).
Lastly, as lhf pointed out in the comments, bitwise operations were added to Lua in version 5.3, and if lhf is the lhf, he should know ;-)

int not returning same value from NSString

I have saved value in Singletone as NSString. When I want to convert to int, value is some random number. For example, I am calling NSString *numberCoupons = [Manager sharedInstance].userProfile.numberOfCoupons, po numberCoupons returning normal value: 40.
But problem is in next line, when I want to convert string to value: int coupons = (int)numberCoupons; It is returning some random number, etc. 421414.
What could be the problem?
try int coupons = [numberCoupons integerValue];
numerofCoupons is obviously an NSNumber object which is used to store numbers within Objective-C collection classes (NSArray, NSDictionary, etc) as only objects can be stored in them.
To get the wrapped value out of the object use:
NSInteger coupons = [numberOfCoupons integerValue]
I would recommend redeclaring numberOfCoupons as NSInteger, and not NSNumber, as NSNumber objects are difficult and expensive to manipulate compared to the primitive types they wrap.
If the value needs to go into a collection class then wrap it in an NSNumber object when adding it and unwrap it when removing it.
When you write (int)numberOfCoupons you are asking that the value in the variable numberOfCoupons be cast to the type int.
Now the value in a variable of type NSString * is a reference to an object, that is a memory address. When (Objective-)C casts a reference to an integer type you get back the memory address. This is the “random” value you are seeing.
What you need to do is send a message to the object referenced by the value in your variable requesting that it return an integer value equivalent to itself. NSString has a method intValue for this, so [numberOfCoupons intValue] will do what you wish.
There is a whole family of xValue methods to obtain various integer and floating-point values of different precision/size.
Note: if you have a reference to an NSNumber, rather than an NSString, then exactly the same code will work.
Note 2: if you do have an NSNumber then the cast expression you first tried may return a value which has a completely different magnitude than you might expect for a memory address. This is because some integer values are represented by special tagged addresses which don't actually reference a real object. This is an optimisation you normally would not notice, except when you accidentally cast the reference value to an integer...
HTH

Efficiency NSString vs NSInteger/int - only for textual representation

I'd like to know if it would make any sense to cast/convert a number, parsed from a csv file, e.g. customer id, to a NSString?
Or maybe better a simple int? As I'm quite new to obj-c, I'm not really sure, wether to consistently use the NSxyz types, or use what I'm used to, coming from Java/C/C++.
Actually the value only is stored in a variable, and then loaded into some textfields (which again would imply a conversion back to NSString I guess?).
Would there be any benefit in less memory being used? Let's assume the ids had 6 digits, parsing roughly 10'000-100'000 customers. Same would apply to smaller numbers, e.g. the addresses street number.
In a string, 1 letter == 1 byte, so if you have 6 digits, you are occupying 6 bytes.
An int instead takes generally 2 (short), 3 or 4 (long) bytes. It can arrive also to 8 bytes with an int_64. But, you are limited because for example in the 2 byte case (16 bit) you can consider 2^16 numbers.
In your case you could use an int, but i would use an NSString, also because you need it in your textfield.
An NSInteger is an int. An NSUInteger is an unsigned int.
An NSNumber is an Object (so no primitive) which can store an int, a float, a double or a boolean. So you can store many type of primitive in this type of variable and then use the appropriate:
[number floatValue];
[number boolValue];
...

Resources