简体   繁体   中英

Transferring a string of characters in quotes to an array of ascii2 bytes in C

How do I easily convert a string of characters in quotes to an array of ascii2 values?

For example:

char ST1[5] = "12345";

to

char DST1[5] = { 0x31, 0x32, 0x33, 0x34, 0x35 }; //string of bytes

Practically nothing.

First, remember that string literals such as "12345" have an extra "null" byte at the end. So instead of treating this array initialization of "12345" to an array of 5 elements, it's really an array of 6 elements, so this initialization statement is more appropriate:

char ST1[6] = "12345";

Or just simply:

char ST1[] = "12345"; // where the size of "6" is auto inferred.

Which is equivalent to:

char DST1[] = {0x31,0x32,0x33,0x34,0x35,0x00};

And once you have an array of 6 elements, you can pass it around as if it had only 5:

So if you have some code that expects to operate on an array of 5 chars:

 void foo(char DST1[])
 {
     for(int i = 0; i < 5; i++)
     { 
         process(DST1[i]);
     }
 }

You can invoke it as follows:

char ST1[]="12345";
foo(ST1);

The only difference between the definitions of ST1 and DST1 is the silent assumption that the target character set is ASCII, at least for the digits.

Here is another alternative:

char CST1[5] = { '1', '2', '3', '4', '5' };

Note however that none of these char arrays are proper C strings because they all lack a null terminator. If you with to define an array that is a C string, you should use this syntax:

char SST1[] = "12345";

Notice the missing length between the [] : the compiler will determine the length of the array from the initializer and add a null terminator, hence a length a 6 .

C strings can be copies with strcpy , char arrays that do not have a null terminator should be copied with memcpy or memmove .

One for all, one answer is casting. Easy way to do it:

int main () {
    int i;
    char ST1[5]="12345";
    for (i=0;i<5;i++)
        printf("%d\n",(int)ST1[i]);
    return 0;
}

Just like I printed, you can store it, calculate using it or anything possible. And as I see, you want those number in hexadecimals. For that, just change the printf 's placeholder with help from here - printf() formatting for hex

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM