Domanda

Ho una variabile intera breve chiamato s_int che contiene value = 2

unsighed short s_int = 2;

voglio copiare questo numero a un array di caratteri per la prima e la seconda posizione di un array di caratteri.

diciamo Let abbiamo char buffer[10];. Vogliamo che i due byte di s_int da copiare a buffer[0] e buffer[1].

Come posso fare?

È stato utile?

Soluzione

Il solito modo per farlo sarebbe quello con gli operatori bit a bit a fetta e tagliarla a dadini, un byte alla volta:

b[0] = si & 0xff;
b[1] = (si >> 8) & 0xff;

anche se questo in realtà dovrebbe essere fatto in un unsigned char, non un char chiaro come sono firmati sulla maggior parte dei sistemi.

Memorizzazione di numeri interi più grandi può essere fatto in un modo simile, o con un ciclo.

Altri suggerimenti

*((short*)buffer) = s_int;

Ma viator emptor che l'ordine dei byte risultante varierà con endianness.

Usando puntatori e calchi.

unsigned short s_int = 2;
unsigned char buffer[sizeof(unsigned short)];

// 1.
unsigned char * p_int = (unsigned char *)&s_int;
buffer[0] = p_int[0];
buffer[1] = p_int[1];

// 2.
memcpy(buffer, (unsigned char *)&s_int, sizeof(unsigned short));

// 3.
std::copy((unsigned char *)&s_int,
          ((unsigned char *)&s_int) + sizeof(unsigned short),
          buffer);

// 4.
unsigned short * p_buffer = (unsigned short *)(buffer); // May have alignment issues
*p_buffer = s_int;

// 5.
union Not_To_Use
{
  unsigned short s_int;
  unsigned char  buffer[2];
};

union Not_To_Use converter;
converter.s_int = s_int;
buffer[0] = converter.buffer[0];
buffer[1] = converter.buffer[1];

I sarebbe memcpy, qualcosa come

memcpy(buffer, &s_int, 2);

L'endianness è conservato correttamente in modo che se lanci di buffer in unsigned short *, si può leggere lo stesso valore del s_int nel modo giusto. Altra soluzione deve essere endian-aware o si potrebbe scambiare LSB e MSB. E, naturalmente, sizeof (breve) deve essere 2.

Se non si vuole fare tutta quella roba bit per bit si potrebbe fare la seguente

char* where = (char*)malloc(10);
short int a = 25232;
where[0] = *((char*)(&a) + 0);
where[1] = *((char*)(&a) + 1);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top