delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1998/10/12/00:50:38

Message-ID: <36218A45.99C1C83D@montana.com>
Date: Sun, 11 Oct 1998 22:49:09 -0600
From: bowman <bowman AT montana DOT com>
X-Mailer: Mozilla 4.5b2 [en] (Win95; I)
X-Accept-Language: en
MIME-Version: 1.0
To: djgpp AT delorie DOT com
Subject: Re: How to convert an unsigned short into a 2 char array?
References: <Pine DOT SOL DOT 3 DOT 91 DOT 981012094000 DOT 8589A-100000 AT mercury>
Reply-To: djgpp AT delorie DOT com


Goh Yong Kwang wrote:
> 
> How do I convert an unsigned short (2 bytes) into a 2 char array?
> Does the following code does the trick?

no, that won't even make it through the compiler. 

try

union {
    unsigned short s;
    char c[2];
} u;


u.s = 0x3132;

printf("c[0] = %c  c[1] = %c\n", u.c[0], u.c[1]);

I doubt that this is what you really want, so you could do

char c[2];
unsigned short s = 0x3132;

c[0] = s >> 8;
c[1] = s & 0xff;

which allows you to determine the order in which the bytes are put into
the char array instead of depending on how a short might be stored on a
given architecture. 

I am not sure this is what you really want to do either, but its what
you asked for.

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019