Cast char to short

天大地大妈咪最大 提交于 2020-01-25 04:58:15

问题


char *buffer; 
short num; 
memcpy(&num, buffer, sizeof(short)); 

*buffer - pointer to the buffer, where number is situated in HEX view. I want to put this number in the variable num without calling memcpy. How can I do it?

number = (short) buffer; //DOESN'T work! 

回答1:


For two byte short:

number = (short)(
           ((unsigned char)buffer[0]) << 8 | 
           ((unsigned char)buffer[1])
          );

For different short:

for (int i = 0; i < sizeof(short); i++)
        number = (number << 8) + ((unsigned char) buffer[i]);

or you'll have some macros for each size.

Also, see tristopia's comment about this making assumptions about endianness.




回答2:


All answers so far suggested using *(short *)buf, but that's not any good - it breaks the strict aliasing rule (the alignment of short is greater than that of char, so you can't do this without invoking undefined behavior).

The short answer is: you'd be better off using memcpy(), but if you really don't want that, then you can use unions and "type punning" (note that this may result in a trap representation of the buffer of bytes which may or may not be what you want):

union type_pun {
    char buf[sizeof(short)];
    short s;
};

union type_pun tp;
tp.buf[0] = 0xff;
tp.buf[1] = 0xaa; // whatever, if `short' is two bytes long
printf("%hd\n", tp.s);



回答3:


Based on your memcpy of sizeof(short) bytes, I'm guessing you want to get the first sizeof(short) bytes from where buffer is pointing at.

number = * (short *) buffer;

will do that for you, as other have pointed out.

You cannot take the pointer's address and put it in a short, so you need to dereference it to get the value in the memory instead.




回答4:


Assuming that with "situated in HEX view" you mean the number is stored in the string like "89AB", you can use the strtol function.

char* end;
num = (short)strtol(buffer, &end, 16);

This function converts the string to a long integer. There is no corresponding function that converts to a short directly, so you'll have to do a (short) anyway, but that wasn't the problem, was it?



来源:https://stackoverflow.com/questions/16851340/cast-char-to-short

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!