View previous topic :: View next topic |
Author |
Message |
FirstSteps
Joined: 09 May 2006 Posts: 7
|
BASIC to C: What is the C equivalent of Mid$ in BASIC |
Posted: Tue May 23, 2006 12:03 pm |
|
|
I need to copy n bytes from anywhere in an array of int8 like the BASIC Mid$ statement. The binary bytes I'm working with may contain the null character. Can someone push me in the right direction? Thanks. |
|
|
rwyoung
Joined: 12 Nov 2003 Posts: 563 Location: Lawrence, KS USA
|
|
Posted: Tue May 23, 2006 12:23 pm |
|
|
strstr() and strcpy() and some pointer manipulation
Or write your own after checking the performance/size of the built in functions. _________________ Rob Young
The Screw-Up Fairy may just visit you but he has crashed on my couch for the last month! |
|
|
PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
|
Posted: Tue May 23, 2006 12:35 pm |
|
|
Use memcpy(). Here's an example that copies 6 bytes from the
middle of the source array to the start of the destination array.
The source data has a Null embedded in the middle of it.
String handling functions won't work with embedded nulls. You need
to use memory handling functions.
The program shown below has this output:
Code: | #include <16F877.H>
#fuses XT, NOWDT, NOPROTECT, BROWNOUT, PUT, NOLVP
#use delay(clock=4000000)
#use rs232(baud=9600, xmit=PIN_C6, rcv=PIN_C7, ERRORS)
int8 source[10] = {1,2,3,4,0,5,6,7,8,9};
int8 dest[10];
//============================
void main()
{
int8 i;
memcpy(dest, &source[2], 6);
for(i = 0; i < 6; i++)
printf("%u ", dest[i]);
while(1);
} |
|
|
|
ckielstra
Joined: 18 Mar 2004 Posts: 3680 Location: The Netherlands
|
|
Posted: Tue May 23, 2006 12:46 pm |
|
|
rwyoung wrote: | strstr() and strcpy() and some pointer manipulation | These are not going to work because...
Quote: | The binary bytes I'm working with may contain the null character. |
Memcpy() is a possible solution. Let's say you have Code: | MyString = "1234567890"
startPos = 3
charCount = 4
Print Mid$(MyString,startPos,charCount) Prints "3456" | you can use Code: | char MyString = "1234567890";
char Dest[10];
int startPos = 3 - 1; // minus 1 because C starts counting at 0
int charCount = 4;
memcpy(&MyString[startPos], Dest, charCount);
Dest[4] = '\0'; Add string terminator
printf("%s", Dest); |
|
|
|
FirstSteps
Joined: 09 May 2006 Posts: 7
|
|
Posted: Tue May 23, 2006 1:11 pm |
|
|
Thanks to all. [bow from waist] |
|
|
ckielstra
Joined: 18 Mar 2004 Posts: 3680 Location: The Netherlands
|
|
Posted: Tue May 23, 2006 1:37 pm |
|
|
Beaten by PCM... Now I had a double post.
I should learn to type faster. |
|
|
|