Re: char array to long

Tilman Schmidt <[email protected]>
Newsgroups gmane.linux.suse.programming
Organization Phoenix Software GmbH
Message-ID <[email protected]>
Jan Hendrik Berlin schrieb:

> Ich hab ein Programmiertechnisches Problem! Wie bekomme ich aus einem char 
> array einen Long Wert?

Das kommt darauf an. (TM)

Was willst Du denn mit der Konversion erreichen? Was steht in dem Array,
und in welchem Zusammenhang soll der gebildete long-Wert damit stehen?

> Mein Vorschlag:
> 
> char c[4];
> long l;
> 
> l=0;
> l=c[0];
> l=l+(c[1]*0x100);
> l=l+(c[2]*0x10000);
> l=l+(c[3]*0x1000000);

Das sieht aus, als ob Du das Array als die vier Bytes eines low endian
32 bit integer interpretieren wolltest. Nur leider ist das (a) recht
ineffizient und behandelt (b) die sign extension falsch.

> Nur leider funkrioniert das nicht so ganz..

Was immer das heißen mag.

> Ich könnte auch einen anderen 
> variablen Typ anstatt char nehmen! Muss nur genau ein Byte groß sein!

Wenn Du

unsigned char c[4];
unsigned long l;

nimmst, dÌrfte obiges funktionieren. Etwas effizienter wÀre das
Horner-Schema:

l = c[3];
l = 0x100 * l + c[2];
l = 0x100 * l + c[1];
l = 0x100 * l + c[0];

-- 
Tilman Schmidt                            [email protected]
Phoenix Software GmbH                             Tel. +49 228 97199 0
Adolf-Hombitzer-Str. 12                           Fax +49 228 97199 99
53227 Bonn, Germany                      http://www.phoenixsoftware.de

-- 
Um die Liste abzubestellen, schicken Sie eine Mail an:
    [email protected]
Um eine Liste aller verfügbaren Kommandos zu bekommen, schicken
Sie eine Mail an: [email protected]
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.