446,305 Members | 1,614 Online
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,305 IT Pros & Developers. It's quick & easy.

# "hello world" to binary representation

 P: n/a Hi, I'm a newbie i want to know how can i convert string to its binary representation, i want to write a program where an example string "hello world" is transformed in his binary representation "11010010101...." and viceversa and then print on the stdout the result of the two representation. thanks in advance, Andrea Feb 19 '07 #1
5 Replies

 P: n/a On 19 Feb, 11:34, "Andrea"

 P: n/a On Feb 19, 12:06 pm, "Salvatore Di Fazio"

 P: n/a On Feb 19, 4:17 am, "Andrea"

 P: n/a "Andrea" On 19 Feb, 11:34, "Andrea" #include int main(void) { const char *message = "hello, world", *cc; char msg_hex[25], msg_org[13], *c, *c2; /* string -hex */ for (cc = message, c = msg_hex; *cc; ++cc, c += 2) { sprintf(c, "%02X", *cc); } *c = 0; /* hex -string */ for (c2 = msg_org, c = msg_hex; *c; c += 2, ++c2) { char tmp = c[2]; c[2] = 0; *c2 = strtol(c, 0, 16); c[2] = tmp; } *c2 = 0; /* print */ printf("message = %s\nmsg_hex = %s\nmsg_org = %s\n", message, msg_hex, msg_org); return 0; } #v- -- Best regards, _ _ .o. | Liege of Serenly Enlightened Majesty of o' \,=./ `o ..o | Computer Science, Michal "mina86" Nazarewicz (o o) ooo +-------ooO--(_)--Ooo-- Feb 22 '07 #5

 P: n/a "Andrea" ok i can use sprintf to transform a string to hexadecimalrepresentation bot how can i back to the original string, with thehexadecimal representation??? Michal Nazarewicz #include int main(void) { const char *message = "hello, world", *cc; char msg_hex[25], msg_org[13], *c, *c2; /* string -hex */ for (cc = message, c = msg_hex; *cc; ++cc, c += 2) { sprintf(c, "%02X", *cc); } *c = 0; /* hex -string */ for (c2 = msg_org, c = msg_hex; *c; c += 2, ++c2) { char tmp = c[2]; c[2] = 0; *c2 = strtol(c, 0, 16); c[2] = tmp; I've just realised that in C99 you can replace those four lines with: #v+ sscanf(c, "%2hhx", c2); #v- however %hhx requires unsigned char not char which may introduce bugs on same implementations. } *c2 = 0; /* print */ printf("message = %s\nmsg_hex = %s\nmsg_org = %s\n", message, msg_hex, msg_org); return 0; } -- Best regards, _ _ .o. | Liege of Serenly Enlightened Majesty of o' \,=./ `o ..o | Computer Science, Michal "mina86" Nazarewicz (o o) ooo +-------ooO--(_)--Ooo-- Feb 22 '07 #6

### This discussion thread is closed

Replies have been disabled for this discussion.