Thread: String Conversion

  1. #1
    Registered User
    Join Date
    Nov 2011
    Posts
    61

    String Conversion

    Hi There,

    I have a string for example

    char string = "D100"

    I need to find a way to convert this to ascii and put each character into a int defined variable in a structure. I'll give an example below.

    char string = "D100"

    converted to ASCII its 44 31 30 30

    i have a structure with defined ints and need to do the following

    send[1]=44
    send[2]=31
    send[3]=30
    send[4]=30

    how do i do this in c

    thanks in advance

    james

  2. #2
    Registered User
    Join Date
    Dec 2011
    Posts
    795
    It's not "converted" to anything. It's stored as ASCII (and then eventually binary).

    So, when you have a "char" array, you can the elements out as any form you want:
    - "%c" ('&')
    - "%d" (38)
    - "%x" (0x26)

  3. #3
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by r_james14 View Post

    how do i do this in c
    Code:
    char string = "D100";
    //or
    char string = { 'D', '1', '0', '0', '\0' };
    //or
    char string = { 44, 31, 30, 30, 0 };
    Are all exactly the same. Note that C strings are null terminated; hence the need for the '\0' at the end. In the first case, this is automatic.

    You could leave the '\0' off if you just want an array of char values, but then do not use any C string functions on it, because it does not count as such.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. String conversion
    By pastitprogram in forum C++ Programming
    Replies: 3
    Last Post: 07-27-2008, 03:41 AM
  2. String conversion
    By tazz25 in forum C++ Programming
    Replies: 9
    Last Post: 09-14-2006, 09:51 AM
  3. Need help with string conversion
    By ahahplz in forum C Programming
    Replies: 8
    Last Post: 02-02-2003, 05:23 PM
  4. string object to null-terminating string conversion
    By sayz0 in forum C++ Programming
    Replies: 2
    Last Post: 11-05-2001, 12:15 PM