I have an array  int16_t arr[4]; . What I want to do is to convert a value in this array to little endian. For example, let us say I have 0x1d02 on the first index, but I need 0x21d there. Is there any elegant way of converting that and writing it back to the array or how are these things done? Note that I just expressed myself in hex, because its easier to see the problem.
            Asked
            
        
        
            Active
            
        
            Viewed 650 times
        
    0
            
            
         
    
    
        Kalybor
        
- 51
- 8
- 
                    I dont know, your 1234 is big endian, now i need that in little endian, so 3412. – Kalybor Dec 13 '20 at 16:47
- 
                    This answer goes over how to reverse a binary number in C: https://stackoverflow.com/questions/9144800/c-reverse-bits-in-unsigned-integer – Blake G Dec 13 '20 at 16:51
- 
                    Your using a signed type instead of unsigned complicates things, but that question addresses the issue. – Shawn Dec 13 '20 at 17:30
2 Answers
0
            
            
        #include <byteswap.h>
arr[0] = bswap_16(arr[0]);
 
    
    
        Bill Lynch
        
- 80,138
- 16
- 128
- 173
- 
                    Should have mentioned i work on a embedded system, thanks for your reply. – Kalybor Dec 13 '20 at 17:03
- 
                    Not portable. Not available on most embedded systems. Not always "magic" libraries or macros are needed., – 0___________ Dec 13 '20 at 17:20
0
            #define BS16(x) (((x) >> 8) | ((x) << 8))
int main(void)
{
    uint16_t arr[] = {0x1122, 0x2233, 0xaabb};
    printf("%hx %hx %hx\n", BS16(arr[0]), BS16(arr[1]), BS16(arr[2]));
    arr[0] = BS16(arr[0]);
}
 
    
    
        0___________
        
- 60,014
- 4
- 34
- 74