Reputation: 1
Been racking my brain for the past few hours but i need help. Pretty much trying to write a C model for a blocking cache to be used in a RTL design. I've defined the cache line in C as an array of 'char' types to make it byte-addressable. Only difficulty is I can't for the life of me figure how to concatenate four bytes (chars) into a 32bit 'int' type to be returned. I've tried everything I could think of using strcat, strncat, strcpy, etc but no luck. strcat returns the proper value when I the char array is populated with actual characters, but it doesn't behave as desired when numbers are use (strcat only returns the first element instead of the entire char array). Example code:
unsigned char aa[4] = {0};
char testet[2] = {1,0};
printf(" aa[0] = %d \n", aa[0]);
printf(" aa[1] = %d \n", aa[1]);
printf(" aa[2] = %d \n", aa[2]);
printf(" aa[3] = %d \n", aa[3]);
printf(" aaconcat as a 32b word is %u \n", *strncat(aa, testet,2));
printf(" aaconcat as a 32b word is %u \n", *strncat(aa, testet,1));
printf(" aa[0] = %d \n", aa[0]);
printf(" aa[1] = %d \n", aa[1]);
printf(" aa[2] = %d \n", aa[2]);
printf(" aa[3] = %d \n", aa[3]);
Returns:
aaconcat as a 32b word is 1
aaconcat as a 32b word is 1
aa[0] = 1
aa[1] = 2
aa[2] = 1
aa[3] = 0
Though I'm expecting {testet[0],testet[1],testet[0]} = 131330.
Upvotes: 0
Views: 4467
Reputation: 1265
if you are trying to concatenate the actual bits, which I suspect you may be trying to do given your expected result from {testet[0],testet[1],testet[0]} = 131330
, then try something like this to concatenate the char
s:
This assumes the char
s you want to concatenate are stored in unsigned char chararr[4]
.
long int chars_in_int = 0;
for (int i = 0; i < 4; i++ ) {
chars_in_int << 8; /* redundant on first loop */
chars_in_int += chararr[i];
}
This will place the char
s with the lowest index in chararr
in the most significant bits of chars_in_int
.
Upvotes: 1