1

I'm searching for a way to convert a word with 4 characters stored as char* to an int and vice versa because i want to transfer the char* through a function which needs an int as argument. Here's an example:

char* word = "abcd";
int number;

// write word in number

char* word2;

// write number in word2

At the end word2 should be the same as word. It would also help me if you know how to convert it in one direction only.

timakro
  • 1,739
  • 1
  • 15
  • 31
  • How long is your `int` in *bytes*? If it is 4 (a typical value), you cannot store 5 random characters in it. – Jongware Dec 13 '14 at 12:35
  • And what integer is equal to "hello"? Sounds more like a problem with your program design. – Baum mit Augen Dec 13 '14 at 12:35
  • If a function takes an `int` parameter, then probably it isn't supposed to accept strings. Perhaps what you wrote is not what you meant to ask? – Stefano Sanfilippo Dec 13 '14 at 12:35
  • actually the char* is exactly 4 characters long. And my int is 4 bytes long, right. – timakro Dec 13 '14 at 12:36
  • [`atoi()`](http://en.cppreference.com/w/cpp/string/byte/atoi)/[`std::ostringstream`](http://en.cppreference.com/w/cpp/io/basic_ostringstream)` – πάντα ῥεῖ Dec 13 '14 at 12:36
  • @πάνταῥεῖ I guess the OP wants to convert a 4-byte string into the correspondig 4-byte integer type, not parse an int from a string. – Stefano Sanfilippo Dec 13 '14 at 12:39
  • 1
    _"actually the char* is exactly 4 characters long"_, nope it's actually 5 bytes long. – πάντα ῥεῖ Dec 13 '14 at 12:39
  • I just want to store the bytes from the char* in an int. The function is for saving and handleing data and accepts ints because i normally need to save them. – timakro Dec 13 '14 at 12:40
  • @Tim I'm afraid you've been chosing the wrong approach. Are you trying to send numbers over the network, or write to files in a compatible manner for different architectures? Then you should have a look at endianess and the `htonl()`,`ntohl()` function family. – πάντα ῥεῖ Dec 13 '14 at 12:44

1 Answers1

3

Assuming it will be converted back on a system with the same endianness

number=*((int*)word);

Convert back:

char word2[5];
*((int*)word2) = number;
word2[4]=0;
Photon
  • 3,182
  • 1
  • 15
  • 16