Deepak
Deepak

Reputation: 107

iOS converting short to bytes of length 2

I have a short variable and i want to convert it to 2 bytes in iOS

short num = 10;
char *bytes;

Now I want to convert this num value into bytes

Please help me

Upvotes: 0

Views: 1571

Answers (4)

MD SHAHIDUL ISLAM
MD SHAHIDUL ISLAM

Reputation: 14523

First of all thanks to baliman, It is working for me after some changes

NSString *myStr = @"2";

char buf[2];

sprintf(buf, "%d", [myStr integerValue]);

char c = buf[0];

Upvotes: 1

Krishnabhadra
Krishnabhadra

Reputation: 34275

May be like this char * bytes = malloc(sizeof(char) * 2);

bytes[0]  =  (char)(num & 0xff);
bytes[1]  =  (char)((num >> 8) & 0xff);

EDIT : After all the comments below..

char * bytes  = malloc(sizeof(char) * 3);

bytes[0]  =  (char)(num & 0xff);
bytes[1]  =  (char)((num >> 8) & 0xff);
bytes[2]  = '\0' ; // null termination

printf("strlen %d", strlen(bytes));
printf("sizeof %d", sizeof(bytes));

Now you can understand the difference..

Upvotes: 3

Matic Oblak
Matic Oblak

Reputation: 16774

Short and 2 bytes is the same thing if short is 16bit, so all you need is to type cast it to whatever you want.. Anyway, if you use this a lot you could use union:

union ShortByteContainer {
    short shortValue;
    char byteValue[2];
};

With it you can transition from short to byte or the other way around:

ShortByteContainer value;
value.shortValue = 13;
char byteVal1 = value.byteValue[0];
char byteVal2 = value.byteValue[1];

value.byteValue[0] = 1;
value.byteValue[1] = 2;
short shortVal = value.shortValue;

Upvotes: 0

baliman
baliman

Reputation: 620

maybe you can do it like this

char buf[2];
short num = 10;
sprintf(buf, "%d", num);

// buf[0] = '1'
// buf[1] = '0'
char c = buf[0];

Johan

Upvotes: 1

Related Questions