delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1997/05/29/00:49:31

From: Erik Max Francis <max AT alcyone DOT com>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: Q: How to get an integer from a char table?
Date: Wed, 28 May 1997 17:56:46 -0700
Organization: Alcyone Systems
Message-ID: <338CD44E.C4AB5CE@alcyone.com>
References: <338b5879 DOT 5940154 AT news DOT abo DOT fi>
NNTP-Posting-Host: newton.alcyone.com
Mime-Version: 1.0
Lines: 37
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

bhallstr AT abo DOT fi wrote:

>         I've made a table namned "foobar" (unsigned char *foobar) and
> a neat variable named "x" (unsigned int x). Then I've loaded some data
> into the table ( of course after mallocating it) Now I want to get a
> 16bit value from the 8bit table to my variable "x". How do I do this?
> x=foobar[10] does not seem to do it.

Depends on just what you mean.  First, under DJGPP, an int is 32 bits, not
16; you'd want a 16-bit unsigned short.  If you want it to be an unsigned
short array, you should have created it as unsigned short *foobar, not
unsigned char *foobar.  If you want the unsigned short to contain the
unsigned char at foobar[10] and in foobar[11], then you could use 

    unsigned short x = *(unsigned short *) (foobar + 10);

However, this brings into question the byte-ordering (high endian or low
endian) of an int on your system.

If the byte ordering is important (which it must be, otherwise you likely
wouldn't be doing this), then you should add them manually, such as 

    unsigned short x = (foobar[10] << 8)|foobar[11];

or

    unsigned short x = (foobar[11] << 8)|foobar[10];

depending on the ordering you desire.

-- 
       Erik Max Francis, &tSftDotIotE / email / max AT alcyone DOT com
                     Alcyone Systems /   web / http://www.alcyone.com/max/
San Jose, California, United States /  icbm / 37 20 07 N  121 53 38 W
                                   \
     "Covenants without the sword / are but words."
                                 / Camden

- Raw text -


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