Ryan Gibson
Ryan Gibson

Reputation: 283

Build String from struct in C

I have just started using C and would appreciate some help.

I have a structure as follows (the IN function etc does not matter for my question):

 void init_itype (uint32_t bits,mips_itype_t *itype) {
  itype->in = bits;
  itype->op = IN(bits,OP_L,OP_SZ);
  itype->opbits = bitstostr(itype->op,OP_SZ,0); 
  itype->rs = IN(bits,RS_L,R_SZ);
  itype->rsbits = bitstostr(itype->rs,R_SZ,0);
  itype->rt = IN(bits,RT_L,R_SZ);
  itype->rtbits = bitstostr(itype->rt,R_SZ,0);
  itype->immediate = IN(bits,I_L,I_SZ);
  itype->ibits = bitstostr(itype->immediate,I_SZ,0); 
  return;
}

I have modified the structure as follows:

printf("Instruction (in binary notation) is : %s%s%s%s\n",
         itype->opbits = "100011",itype->rsbits,itype->rtbits,itype->ibits);

I printed the whole string just to make sure that it was behaving the way it should be.

What I'm wondering is how can I can store the opbits, rsbits, rtbits and ibits in a single array so that I have the new binary pattern as a string?

Upvotes: 1

Views: 61

Answers (1)

cnicutar
cnicutar

Reputation: 182754

You are likely looking for snprintf. It's like printf only it "prints" to a string.

char str[LENGTH];
snprintf(str, sizeof str, "%s%s%s%s", ...);

Upvotes: 2

Related Questions