tags:

views:

190

answers:

3

Hi

I have an string (iso 8859-1) with some non ascii chars, any idea how i cast to an integer or binary?

example

str has this text: "value 5= \377\242\242"

I need to transform \377\242\242 to binary (i tried with atol or strtol but doesn´t work)

Thanks

+4  A: 

The characters are already numbers/binary - in C, a character is an integer type.

What might be confusing you is that the string literal "\377\242\242" has 3 characters, not 12. In C, a \ followed by 1-3 digits between 0-7 is an octal escape sequence.

If you index intro the string "\377\242\242", you get the following results (pseudo code) :

"\377\242\242"[0] == 255 == '\377';

"\377\242\242"[1] == 162 == '\242';

"\377\242\242"[2] == 162 == '\242';

Take a look here for details of C character literals.

Joe Gauterin
A: 

The fact that ascii and binary are mixed means it's non-standard.
So you have to play by the conventions: if the convention says that after the "value 5 = " string there is a little-endian 4 bytes integer, you could put a pointer there and cast to an integer if you work on a little-endian system.

In your case (3 bytes)

int threeBytesToInt(char* p)
{
  return ((unsigned int)p[0]) * (255L * 255L) + ((unsigned int)p[1]) * 255L + ((unsigned int)p[2]);
}

could do the trick given the right convention

If possible, avoid these constructs or go for a "clean" convention to minimize portability issues. In a clean convention, the format of the binary data would be described in the ascii part.

stefaanv
A: 

I'm confused by your requirements.

According to the ISO 8859 table, the octal values 377, and 242 do not represent numerical characters, e.g. '0' through '9'. Thus using strtoul is out of the question to convert the 3 characters into one integral number.

The octal values 377, 242 and 242 represent 3 8-bit quantites or 24 bits total. This bit quantity is not a power of 2, so I guess you don't all the bits converted to binary. (Although 24 bits is common for describing color values).

Do you want the values to displayed as binary textual numbers, such as '11111111' for octal 377? If this is the case, use std::strtoul using 2 as the base.

Otherwise, please clarify your requirements or question. Give an example program fragment that shows what you want to achieve (pseudo code would work also).

Thomas Matthews