Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.c > #28994

Re: Saving an unsigned short integer to string

From Keith Thompson <kst-u@mib.org>
Newsgroups comp.lang.c
Subject Re: Saving an unsigned short integer to string
Date 2012-12-06 12:25 -0800
Organization None to speak of
Message-ID <lnk3svorlw.fsf@nuthaus.mib.org> (permalink)
References <1qd1c8psp6ut5ipmhb7q86hbbjrmpcg5pf@4ax.com> <k9qfav$ipa$1@dont-email.me> <k9qgip$ohe$1@dont-email.me>

Show all headers | View raw


Rui Maciel <rui.maciel@gmail.com> writes:
> Rui Maciel wrote:
>> union Foo
>> {
>> int i;
>> char mytext[2];
>> };
>
> It must be said that it isn't a good idea to use the char and int data type, 
> because the number of bits that are used to define those types are platform-
> dependent.
>
> Considering the range that was mentioned, which was 0-65535, the following 
> union might be more appropriate:
>
> union Foo 
> {
>         uint16_t i;
>         uint8_t mytext[2];
> };

That's certainly better than using int, but byte ordering varies from
one system to another.  Storing a value in i could result in the
high-order byte being stored in mytext[0] and the low-order byte in
mytext[1], or vice versa.  If you want to be able to share the byte
values across different systems, you'll want to control the byte order
yourself -- which is why we have "network byte order".

See http://en.wikipedia.org/wiki/Endianness

-- 
Keith Thompson (The_Other_Keith) kst-u@mib.org  <http://www.ghoti.net/~kst>
    Will write code for food.
"We must do something.  This is something.  Therefore, we must do this."
    -- Antony Jay and Jonathan Lynn, "Yes Minister"

Back to comp.lang.c | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread


Thread

Saving an unsigned short integer to string Test <test@.nil.invalid.com> - 2012-12-06 17:24 +0200
  Re: Saving an unsigned short integer to string Eric Sosman <esosman@comcast-dot-net.invalid> - 2012-12-06 10:45 -0500
  Re: Saving an unsigned short integer to string Rui Maciel <rui.maciel@gmail.com> - 2012-12-06 15:58 +0000
    Re: Saving an unsigned short integer to string Rui Maciel <rui.maciel@gmail.com> - 2012-12-06 16:19 +0000
      Re: Saving an unsigned short integer to string Keith Thompson <kst-u@mib.org> - 2012-12-06 12:25 -0800
        Re: Saving an unsigned short integer to string Fred K <fred.l.kleinschmidt@gmail.com> - 2012-12-06 14:16 -0800
          Re: Saving an unsigned short integer to string Rui Maciel <rui.maciel@gmail.com> - 2012-12-06 23:23 +0000
  Re: Saving an unsigned short integer to string pete <pfiland@mindspring.com> - 2012-12-07 00:37 -0500
  Re: Saving an unsigned short integer to string Malcolm McLean <malcolm.mclean5@btinternet.com> - 2012-12-08 10:53 -0800

csiph-web