2

I've been trying to do this but I wasn't able to find any good source for it.

Basicly, I want to convert a char* variable (byte array) into an int and vis-versa. Thanks.

1
  • 2
    The question is vague as you do not specify how the contents of the array should be processed. There are at least three interpretations, including pointer casting, string conversion, and handling of byte array as 8-bit integers. Commented Jan 15, 2011 at 5:12

2 Answers 2

2

To convert from string to integer you can use atoi function and sprintf to do it in other direction.

UPDATE (see comments):

Than you need to do following

char *word = "Hello world";
int ints[11];
for(int i=0; i<strlen(word); ++i)
        ints[i] = (int)word[i];
Sign up to request clarification or add additional context in comments.

5 Comments

I was speaking of bitwise operators. Not string like convertions.
What do you mean? Providing an example of what sort of data would be in the char*, and what sort of int you expect to end up with, would help. "bitwise operators" in this case don't seem to make any sense, so the question must be unclear.
well, let's say I just read 4 bytes of a file. They're stored into char* and I'd like to make it an int. And I'd also like to turn an int into a char[4]. Not converting a number to a numerical string value.
but what do you mean stored in char* ? How do you read from file? you can use fscanf with a specified format string to read binary data from the file.
I would like to notice that char data type is actually an 1 byte integer value [0,255]. So you can cast char to int and back.
1

If you're trying to convert a byte array into an int it is sufficient to use a reinterpret_cast. Technically, this is UB, but if you know the bytes are in the right format, it usually results in exactly what you're asking for.

This is while noting the difference between a char* STRING and a char* BYTE ARRAY.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.