|
From: Per W. <pw...@ia...> - 2003-03-05 12:05:58
|
The shift operators are of course defiend for both signed and unsigned
data types.
It's just that for >> you may not assume if it will shift in a '0' or a
'1' in the most significant bit fir signed integers, i.e.
-3 (0xfffd) >> 1 =3D 32766 (0x7ffe)
-3 (0xfffd) >> 1 =3D -2 (0xfffe)
depending on implementation.
However, when shifting in characters into a 32-bit integer, I don't have
to care about this, since << always shifts in 0 in the least significant
bit.
/Per W
On Wed, 5 Mar 2003, Ioannis Vranos wrote:
> Some adjustments:
>
>
>
> -------Original Message-------
>
> From: Ioannis Vranos
> Date: =D4=E5=F4=DC=F1=F4=E7, 5 =CC=DC=F1=F4=E9=EF=F2 2003 12:55:26 =F0=EC
> To: Dev-C++ Mailing List
> Subject: Re: [Dev-C++] Character variables
>
> -------Original Message-------
>
> From: Per Westermark
> Date: =D4=E5=F4=DC=F1=F4=E7, 5 =CC=DC=F1=F4=E9=EF=F2 2003 12:26:51 =F0=EC
> To: Giligun
> Cc: C++
> Subject: Re: [Dev-C++] Character variables
>
> short s =3D 'ab';
> int i =3D 'abcd';
>
> given that int is 4 byte.
>
>
> =3D=3D> That isn't valid C++. And where it gets compiled you can't consid=
er it
> as safe.
>
>
>
> But a lot of compilers will give you warnings, since it you can't be sure
> if memcpy(buf,&s,sizeof(s)) will give you
> buf[0] =3D 'a', buf[1] =3D 'b';
> or
> buf[0] =3D 'b', buf[1] =3D 'a';
>
> In short - be very careful about using this feature. One place where it's
> elegant to use is if you are reading a tagged file, where each tag is
> 4-byte long:
> char *buf;
>
> int tag =3D 0;
> for (i =3D 0; i < 4; i++) {
> tag =3D (tag << 8) | *buf++;
> }
>
>
> =3D=3D> Too system dependent. Additionally bitwise operators are to be us=
ed in
> unsigned integrals only.
>
> =3D=3D> He could use wchar_t instead. But since he wants to store charact=
ers
> (assuming in the range 0-127) he can use a char sequence nicely and easil=
y.
>
>
> switch (tag) {
> case 'STRT': ...; break;
> case 'HEDR': ...; break;
> case 'DATA': ...; break;
> case 'ENDF': ...; break;
> }
>
> If there are a lot of tags, the result is a very fast matching of the
> tags.
>
>
> =3D=3D> By the way i would do something like the above using std::bitset.
>
>
>
> Ioannis Vranos
>
> * Programming pages: http://www.noicys.freeurl.com
> * Alternative URL: http://run.to/noicys
|