Convert int to bytes and efficient endian inclusion

I need to do some int → byte conversion and switch to a big endian for some MIDI data that I write. Right now, I'm doing it like:

int tempo = 500000;
char* a = (char*)&tempo;

//reverse it
inverse(a, 3);

[myMutableData appendBytes:a length:3];

and inverse function:

void inverse(char inver_a[],int j)
{
    int i,temp;
    j--;
    for(i=0;i<(j/2);i++)
    {
      temp=inver_a[i];
      inver_a[i]=inver_a[j];
      inver_a[j]=temp;
       j--;
     }
}

This works, but it is not very clean, and I do not like that I need to specify 3both times (since I have the luxury to know how many bytes it will end).

Is there a more convenient way that I should approach this?

+3
source share
3 answers

Use the functions Basic byte exchange functions .

int32_t unswapped = 0x12345678;
int32_t swapped = CFSwapInt32HostToBig(unswapped);
char* a = (char*) &swapped;
[myMutableData appendBytes:a length:sizeof(int32_t)];
+14
source
int tempo = 500000;

//reverse it
inverse(&tempo);

[myMutableData appendBytes:(char*)tempo length:sizeof(tempo)];

and inverse function:

void inverse(int *value)
{
    char inver_a = (char*)value;
    int j = sizeof(*value); //or u can put 2
    int i,temp;
    // commenting this j--;
    for(i=0;i<(j/2);i++)
    {
      temp=inver_a[i];
      inver_a[i]=inver_a[j];
      inver_a[j]=temp;
       j--;
     }
}
0
source

:

/*
  Quick swap of Endian.    
*/

#include <stdio.h>

int main(){

  unsigned int number = 0x04030201;
  char *p1, *p2;
  int i;

    p1 = (char *) &number;
    p2 = (p1 + 3);


  for (i=0; i<2; i++){
      *p1 ^= *p2;
      *p2 ^= *p1;
      *p1 ^= *p2;
  }


return 0;   
}

, . :)

, :)

0

All Articles