How to convert bytes to string in C programming

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • parvathireddy
    New Member
    • Jan 2014
    • 8

    How to convert bytes to string in C programming

    could anyone explain me how to convert bytes of data to string using c programming , would be very thankful. I searched but i didnt get appropriate one .


    Example : 112131(bytes) to string ("some sample")
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    If by bytes you mean a series of ASCII digits then you put/copy the digits into an array of char and add a zero terminator to the end of it

    Code:
    char bytes[] = {'1', '1', '2', '1', '3', '1'};
    char string[11];
    
    memcpy(string, bytes, sizeof bytes);
    string[sizeof bytes] = '\0';
    If you mean binary data you can use sprintf

    Code:
    int bytes = 112131;
    char string[11];
    
    sprintf(string, "%d", bytes);

    Comment

    • parvathireddy
      New Member
      • Jan 2014
      • 8

      #3
      Thank you, Banfa .

      But we tried with that one and its nt working here. is there any alternative apart from this. I am using visual studio 2010 IDE

      Comment

      • Banfa
        Recognized Expert Expert
        • Feb 2006
        • 9067

        #4
        Which one?

        Also there is not reason that either of those should fail to work on any platform since they are both portable.

        This would be easier if you posted a snippet of your code showing what you are attempting.

        Comment

        • donbock
          Recognized Expert Top Contributor
          • Mar 2008
          • 2427

          #5
          @parvathireddy: please clarify your example.

          Are you saying that you want a program that would convert the three bytes 0x11, 0x21, and 0x31 into the 11-character (plus null) string "some sample"?

          Comment

          Working...