简体   繁体   中英

Converting Bytes to signed short and int value to bytes

I have int values of two bytes for example 254 = 0xFE, 112 = 0x70 . I need to convert them to signed short. Now the signed short value should be -400.

And then after changing that value I have an integer for example -410 that i need to convert back to two bytes.

How could i achieve that for iOS?

If the bytes are in the native architecture endianness , then it's as simple as

uint8_t *p = someAddress;
short value = *(short *)p;

value = 410;
*(short *)p = value;

However if the bytes are in a foreign endianness you are required to convert each byte of the integer, which is slow. Here is one, of many, examples.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM