Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,943 questions

55,787 answers

573 users

How to convert string to byte array in C

1 Answer

0 votes
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

// Function to create a dynamic byte array from a string
unsigned char* createByteArray(const char* str, size_t* len) {
    *len = strlen(str);
    unsigned char* byteArray = (unsigned char*)malloc(*len + 1); // +1 for the null terminator
    if (byteArray == NULL) {
        printf("Memory allocation failed\n");
        return NULL;
    }
    memcpy(byteArray, str, *len + 1);
    
    return byteArray;
}

int main() {
    char* str = "C Programming";
    size_t len = 0;

    // Eventually, it's the same array...
    unsigned char* byteArray = createByteArray(str, &len);
    if (byteArray == NULL) {
        return 1; // Exit the program if allocation failed
    }

    for (size_t i = 0; i < len + 1; i++) {
        printf("%02x ", byteArray[i]);
    }
    printf("\n");

    // Free the allocated memory
    free(byteArray);

    return 0;
}


 
/*
run:
 
43 20 50 72 6f 67 72 61 6d 6d 69 6e 67 00 
 
*/

 



answered Mar 10, 2025 by avibootz
edited Mar 10, 2025 by avibootz

Related questions

1 answer 143 views
1 answer 124 views
2 answers 163 views
163 views asked Feb 14, 2025 by avibootz
1 answer 113 views
113 views asked Mar 30, 2025 by avibootz
1 answer 115 views
115 views asked Mar 29, 2025 by avibootz
1 answer 207 views
1 answer 295 views
...