468,107 Members | 1,319 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,107 developers. It's quick & easy.

Binary number

How do I display an integer in binary format in C?

e.g. 4 displayed as "100"
Nov 14 '05 #1
23 4714
Davey wrote:

How do I display an integer in binary format in C?

e.g. 4 displayed as "100"


Here's one common way to do it:

1) reserve enough storage for a string that can contain the whole
result.
If your integer is an unsigned long int, say, then you know that it
can't have more than sizeof(long int) * CHAR_BIT value bits, so just
define an array of char, sizeof(long int) * CHAR_BIT + 1 bytes in
length.

2) point to the start of the string.

3) if the number is even, write '0' through the pointer. Otherwise,
write '1' through the pointer.

4) increment the pointer.

5) divide the number by 2.

6) if the number is non-zero, continue from step 3).

7) write '\0' through the pointer, to null-terminate the string.

8) reverse the string, taking care to leave the terminator in place.
Nov 14 '05 #2
Davey wrote:
How do I display an integer in binary format in C?

e.g. 4 displayed as "100"

You should try it yourself.

void bits(uchar b, int n) {
for (--n; n >= 0; --n)
putchar((b & 1 << n) ? '1' : '0');
putchar(' ');
}

The above is not a program, but a clue.
--
Joe Wright mailto:jo********@comcast.net
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Nov 14 '05 #3

Davey wrote:
How do I display an integer in binary format in C?

e.g. 4 displayed as "100"

#include <stdio.h>
#include <limits.h>

#define SHOWBITS(var) bitshow((unsigned char *)&var, sizeof(var))

int bitshow(unsigned char *p, int size)
{
int count = 0;
int byte;
while(size)
{
byte = CHAR_BIT;
while(byte > 0)
{
if(*p & 1 << byte)
{
putchar('1');
count++;
}
else putchar('0');

byte--;
}
putchar('\n');
size--;
p++;
}
return count;
}

int main(void)
{
int i= 0xFD1;

SHOWBIT(i); /* returns number of set bits, discarded */

puts("Press ENTER when done"), getchar();
return 0;
}

Nov 14 '05 #4
Davey wrote:
How do I display an integer in binary format in C?

e.g. 4 displayed as "100"

I thought this sounded familar, so I looked in my archives and sure
enough, there it was. I can't believe almost 11 years have gone by!

/************************************************** *************/
/* File Id: bin.c. */
/* Author: Stan Milam. */
/* Date Written: 28-Apr-94. */
/* */
/* This program will print an unsigned integer value entered on*/
/* the command line in it binary format. */
/* */
/************************************************** *************/

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

int main( int argc, char **argv ) {

unsigned value, rv, mask, i;

/************************************************** *********/
/* Check to see if command line args used. If not give tell*/
/* user how the program works. */
/************************************************** *********/

if ( argc < 2 ) {
fputs("Usage: BIN integer_number\n", stderr);
return 1;
}

/************************************************** *********/
/* Determine the mask. Done this way to be portable. Also */
/* Extract the value from command line. */
/************************************************** *********/

mask = 1 << sizeof(unsigned) * CHAR_BIT - 1;
value = (unsigned) strtol(argv[1], NULL, 0);

/************************************************** *********/
/* For each possible bit determine its state and print. */
/************************************************** *********/

for ( i = 0; i < sizeof(unsigned) * CHAR_BIT; i++ ) {
rv = (value & mask) >> (sizeof(unsigned) * CHAR_BIT - 1);
value <<= 1;
printf("%d", rv);
}

printf("\n");
return 0;
}
Nov 14 '05 #5
Stan Milam wrote:
Davey wrote:
How do I display an integer in binary format in C?

e.g. 4 displayed as "100"


I thought this sounded familar, so I looked in my archives and sure
enough, there it was. I can't believe almost 11 years have gone by!

/************************************************** *************/
/* File Id: bin.c. */
/* Author: Stan Milam. */
/* Date Written: 28-Apr-94. */
/* */
/* This program will print an unsigned integer value entered on*/
/* the command line in it binary format. */
/* */
/************************************************** *************/

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

int main( int argc, char **argv ) {

unsigned value, rv, mask, i;

/************************************************** *********/
/* Check to see if command line args used. If not give tell*/
/* user how the program works. */
/************************************************** *********/

.... snip code ...

Here is something more generalized, with testing code. Also been
around a while in various guises.

/* Routines to display values in various bases */
/* with some useful helper routines. */
/* by C.B. Falconer, 19 Sept. 2001 */
/* Released to public domain. Attribution appreciated */

#include <stdio.h>
#include <string.h>
#include <limits.h> /* ULONG_MAX etc. */

/* ======================= */
/* reverse string in place */
size_t revstring(char *stg)
{
char *last, temp;
size_t lgh;

lgh = strlen(stg);
if (lgh > 1) {
last = stg + lgh; /* points to '\0' */
while (last-- > stg) {
temp = *stg; *stg++ = *last; *last = temp;
}
}
return lgh;
} /* revstring */

/* ============================================ */
/* Mask and convert digit to hex representation */
/* Output range is 0..9 and a..f only */
int hexify(unsigned int value)
{
static char hexchars[] = "0123456789abcdef";

return (hexchars[value & 0xf]);
} /* hexify */

/* ================================================== */
/* convert unsigned number to string in various bases */
/* 2 <= base <= 16, controlled by hexify() */
/* Returns actual output string length */
size_t basedisplay(unsigned long number, unsigned int base,
char *stg, size_t maxlgh)
{
char *s;

/* assert (stg[maxlgh]) is valid storage */
s = stg;
if (maxlgh && base)
do {
*s = hexify(number % base);
s++;
} while (--maxlgh && (number = number / base) );
*s = '\0';
revstring(stg);
return (s - stg);
} /* basedisplay */

/* ================================================ */
/* convert signed number to string in various bases */
/* 2 <= base <= 16, controlled by hexify() */
/* Returns actual output string length */
size_t signbasedisplay(long number, unsigned int base,
char * stg, size_t maxlgh)
{
char *s;
size_t lgh;
unsigned long n;

s = stg; lgh = 0;
n = (unsigned long)number;
if (maxlgh && (number < 0L)) {
*s++ = '-';
maxlgh--;
n = -(unsigned long)number;
lgh = 1;
}
lgh = lgh + basedisplay(n, base, s, maxlgh);
return lgh;
} /* signbaseddisplay */
/* ==================== */
/* flush to end-of-line */
int flushln(FILE *f)
{
int ch;

while ('\n' != (ch = fgetc(f)) && (EOF != ch)) /* more */;
return ch;
} /* flushln */

/* ========== END of generically useful routines ============ */

/* ========================= */
/* Prompt and await <return> */
static void nexttest(char *prompt)
{
static char empty[] = "";

if (NULL == prompt) prompt = empty;
printf("\nHit return for next test: %s", prompt);
fflush(stdout);
flushln(stdin);
} /* nexttest */

/* ============================== */
/* Display a value and its length */
static void show(char *caption, int sz, char *stg)
{

if ((unsigned)sz != strlen(stg))
printf("Something is wrong with the sz value\n");
printf("%s: sz = %2d \"%s\"\n", caption, sz, stg);
} /* show */

/* =========== */
/* exercise it */
int main(void)
{
#define LGH 40
#define VALUE 1234567890

char stg[LGH];
unsigned int base;
int sz;

printf("\nExercising basedisplay routine\n");
printf("\nbase sz value\n");
for (base = 2; base <= 16; base++) {
sz = (int)basedisplay(VALUE, base, stg, LGH - 1);
printf("%2d %2d %s\n", base, sz, stg);
}

nexttest("ULONG_MAX");
for (base = 8; base <= 16; base++) {
sz = (int)basedisplay(ULONG_MAX, base, stg, LGH - 1);
printf("%2d %2d %s\n", base, sz, stg);
}

basedisplay(0, 10, stg, 3);
printf("\nzero %s\n", stg);

basedisplay(VALUE, 10, stg, 3);
printf("3 lsdigits only, base 10 %s\n", stg);

printf("\nBad calls:\n");

sz = (int)basedisplay(VALUE, 10, stg, 0);
show("0 length field", sz, stg);

sz = (int)basedisplay(VALUE, 1, stg, 20);
show("base 1, lgh 20", sz, stg);

sz = (int)basedisplay(VALUE, 0, stg, 20);
show("base 0, lgh 20", sz, stg);

sz = (int)signbasedisplay(-1234, 10, stg, 0);
show("0 lgh fld, -ve", sz, stg);

sz = (int)signbasedisplay(-1234, 10, stg, 2);
show("truncate -1234", sz, stg);

nexttest("System limits");

sz = (int)signbasedisplay(SCHAR_MIN, 10, stg, 20);
show("SCHAR_MIN ", sz, stg);

sz = (int)signbasedisplay(SCHAR_MAX, 10, stg, 20);
show("SCHAR_MAX ", sz, stg);

sz = (int)signbasedisplay(UCHAR_MAX, 10, stg, 20);
show("UCHAR_MAX ", sz, stg);

sz = (int)signbasedisplay(CHAR_MIN, 10, stg, 20);
show("CHAR_MIN ", sz, stg);

sz = (int)signbasedisplay(CHAR_MAX, 10, stg, 20);
show("CHAR_MAX ", sz, stg);

sz = (int)signbasedisplay(MB_LEN_MAX, 10, stg, 20);
show("MB_LEN_MAX ", sz, stg);

sz = (int)signbasedisplay(SHRT_MIN, 10, stg, 20);
show("SHRT_MIN ", sz, stg);

sz = (int)signbasedisplay(SHRT_MAX, 10, stg, 20);
show("SHRT_MAX ", sz, stg);

sz = (int)signbasedisplay(USHRT_MAX, 10, stg, 20);
show("USHRT_MAX ", sz, stg);

sz = (int)signbasedisplay(INT_MIN, 10, stg, 20);
show("INT_MIN ", sz, stg);

sz = (int)signbasedisplay(INT_MAX, 10, stg, 20);
show("INT_MAX ", sz, stg);

sz = (int)signbasedisplay(INT_MAX, 10, stg, 20);
show("INT_MAX ", sz, stg);

sz = (int) basedisplay(UINT_MAX, 10, stg, 20);
show("UINT_MAX ", sz, stg);

sz = (int)signbasedisplay(LONG_MIN, 10, stg, 20);
show("LONG_MIN ", sz, stg);

sz = (int)signbasedisplay(LONG_MAX, 10, stg, 20);
show("LONG_MAX ", sz, stg);

sz = (int) basedisplay(ULONG_MAX, 10, stg, 20);
show("ULONG_MAX ", sz, stg);

nexttest("DONE");
return 0;
} /* main */

--
"If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
Nov 14 '05 #6
Davey wrote:
How do I display an integer in binary format in C?

e.g. 4 displayed as "100"


void dump(unsigned x)
{
unsigned m;
if (x == 0) m = 1;
else for (m = -1u/2+1; !(x & m); m >>= 1) ;
do { putchar('0' + !!(x & m)); } while (m >>= 1);
}

--
Peter

Nov 14 '05 #7
CBFalconer wrote:
Stan Milam wrote:
Davey wrote:

How do I display an integer in binary format in C?

e.g. 4 displayed as "100"


I thought this sounded familar, so I looked in my archives and sure
enough, there it was. I can't believe almost 11 years have gone by!

/************************************************** *************/
/* File Id: bin.c. */
/* Author: Stan Milam. */
/* Date Written: 28-Apr-94. */
/* */
/* This program will print an unsigned integer value entered on*/
/* the command line in it binary format. */
/* */
/************************************************** *************/

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

int main( int argc, char **argv ) {

unsigned value, rv, mask, i;

/************************************************** *********/
/* Check to see if command line args used. If not give tell*/
/* user how the program works. */
/************************************************** *********/


... snip code ...

Here is something more generalized, with testing code. Also been
around a while in various guises.

/* Routines to display values in various bases */
/* with some useful helper routines. */
/* by C.B. Falconer, 19 Sept. 2001 */
/* Released to public domain. Attribution appreciated */

#include <stdio.h>
#include <string.h>
#include <limits.h> /* ULONG_MAX etc. */

/* ======================= */
/* reverse string in place */
size_t revstring(char *stg)
{
char *last, temp;
size_t lgh;

lgh = strlen(stg);
if (lgh > 1) {
last = stg + lgh; /* points to '\0' */
while (last-- > stg) {
temp = *stg; *stg++ = *last; *last = temp;
}
}
return lgh;
} /* revstring */

/* ============================================ */
/* Mask and convert digit to hex representation */
/* Output range is 0..9 and a..f only */
int hexify(unsigned int value)
{
static char hexchars[] = "0123456789abcdef";

return (hexchars[value & 0xf]);
} /* hexify */

/* ================================================== */
/* convert unsigned number to string in various bases */
/* 2 <= base <= 16, controlled by hexify() */
/* Returns actual output string length */
size_t basedisplay(unsigned long number, unsigned int base,
char *stg, size_t maxlgh)
{
char *s;

/* assert (stg[maxlgh]) is valid storage */
s = stg;
if (maxlgh && base)
do {
*s = hexify(number % base);
s++;
} while (--maxlgh && (number = number / base) );
*s = '\0';
revstring(stg);
return (s - stg);
} /* basedisplay */

/* ================================================ */
/* convert signed number to string in various bases */
/* 2 <= base <= 16, controlled by hexify() */
/* Returns actual output string length */
size_t signbasedisplay(long number, unsigned int base,
char * stg, size_t maxlgh)
{
char *s;
size_t lgh;
unsigned long n;

s = stg; lgh = 0;
n = (unsigned long)number;
if (maxlgh && (number < 0L)) {
*s++ = '-';
maxlgh--;
n = -(unsigned long)number;
lgh = 1;
}
lgh = lgh + basedisplay(n, base, s, maxlgh);
return lgh;
} /* signbaseddisplay */
/* ==================== */
/* flush to end-of-line */
int flushln(FILE *f)
{
int ch;

while ('\n' != (ch = fgetc(f)) && (EOF != ch)) /* more */;
return ch;
} /* flushln */

/* ========== END of generically useful routines ============ */

/* ========================= */
/* Prompt and await <return> */
static void nexttest(char *prompt)
{
static char empty[] = "";

if (NULL == prompt) prompt = empty;
printf("\nHit return for next test: %s", prompt);
fflush(stdout);
flushln(stdin);
} /* nexttest */

/* ============================== */
/* Display a value and its length */
static void show(char *caption, int sz, char *stg)
{

if ((unsigned)sz != strlen(stg))
printf("Something is wrong with the sz value\n");
printf("%s: sz = %2d \"%s\"\n", caption, sz, stg);
} /* show */

/* =========== */
/* exercise it */
int main(void)
{
#define LGH 40
#define VALUE 1234567890

char stg[LGH];
unsigned int base;
int sz;

printf("\nExercising basedisplay routine\n");
printf("\nbase sz value\n");
for (base = 2; base <= 16; base++) {
sz = (int)basedisplay(VALUE, base, stg, LGH - 1);
printf("%2d %2d %s\n", base, sz, stg);
}

nexttest("ULONG_MAX");
for (base = 8; base <= 16; base++) {
sz = (int)basedisplay(ULONG_MAX, base, stg, LGH - 1);
printf("%2d %2d %s\n", base, sz, stg);
}

basedisplay(0, 10, stg, 3);
printf("\nzero %s\n", stg);

basedisplay(VALUE, 10, stg, 3);
printf("3 lsdigits only, base 10 %s\n", stg);

printf("\nBad calls:\n");

sz = (int)basedisplay(VALUE, 10, stg, 0);
show("0 length field", sz, stg);

sz = (int)basedisplay(VALUE, 1, stg, 20);
show("base 1, lgh 20", sz, stg);

sz = (int)basedisplay(VALUE, 0, stg, 20);
show("base 0, lgh 20", sz, stg);

sz = (int)signbasedisplay(-1234, 10, stg, 0);
show("0 lgh fld, -ve", sz, stg);

sz = (int)signbasedisplay(-1234, 10, stg, 2);
show("truncate -1234", sz, stg);

nexttest("System limits");

sz = (int)signbasedisplay(SCHAR_MIN, 10, stg, 20);
show("SCHAR_MIN ", sz, stg);

sz = (int)signbasedisplay(SCHAR_MAX, 10, stg, 20);
show("SCHAR_MAX ", sz, stg);

sz = (int)signbasedisplay(UCHAR_MAX, 10, stg, 20);
show("UCHAR_MAX ", sz, stg);

sz = (int)signbasedisplay(CHAR_MIN, 10, stg, 20);
show("CHAR_MIN ", sz, stg);

sz = (int)signbasedisplay(CHAR_MAX, 10, stg, 20);
show("CHAR_MAX ", sz, stg);

sz = (int)signbasedisplay(MB_LEN_MAX, 10, stg, 20);
show("MB_LEN_MAX ", sz, stg);

sz = (int)signbasedisplay(SHRT_MIN, 10, stg, 20);
show("SHRT_MIN ", sz, stg);

sz = (int)signbasedisplay(SHRT_MAX, 10, stg, 20);
show("SHRT_MAX ", sz, stg);

sz = (int)signbasedisplay(USHRT_MAX, 10, stg, 20);
show("USHRT_MAX ", sz, stg);

sz = (int)signbasedisplay(INT_MIN, 10, stg, 20);
show("INT_MIN ", sz, stg);

sz = (int)signbasedisplay(INT_MAX, 10, stg, 20);
show("INT_MAX ", sz, stg);

sz = (int)signbasedisplay(INT_MAX, 10, stg, 20);
show("INT_MAX ", sz, stg);

sz = (int) basedisplay(UINT_MAX, 10, stg, 20);
show("UINT_MAX ", sz, stg);

sz = (int)signbasedisplay(LONG_MIN, 10, stg, 20);
show("LONG_MIN ", sz, stg);

sz = (int)signbasedisplay(LONG_MAX, 10, stg, 20);
show("LONG_MAX ", sz, stg);

sz = (int) basedisplay(ULONG_MAX, 10, stg, 20);
show("ULONG_MAX ", sz, stg);

nexttest("DONE");
return 0;
} /* main */


CB, keep it small, keep it simple, keep it readable and you will be more
productive and live longer.

Stan.
Nov 14 '05 #8
Stan Milam wrote:
CBFalconer wrote:
<snip>
CB, keep it small, keep it simple, keep it readable and you
will be more productive and live longer.


Any reason why you quoted the whole thing?

Your post would be more productive if you pointed out the
issue with LONG_MIN within CBF's code. ;)

--
Peter

Nov 14 '05 #9
Peter Nilsson wrote:
Stan Milam wrote:
CBFalconer wrote:


<snip>
CB, keep it small, keep it simple, keep it readable and you
will be more productive and live longer.


Any reason why you quoted the whole thing?

Your post would be more productive if you pointed out the
issue with LONG_MIN within CBF's code. ;)


What issue? A value of LONG_MIN is immediately converted to an
unsigned long with a '-' sign emitted.

--
"If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
Nov 14 '05 #10
CBFalconer wrote:
...
What issue? A value of LONG_MIN is immediately converted to an
unsigned long with a '-' sign emitted.


The conversion of LONG_MIN to unsigned long may yield 0.

It's not likely to on any implementation in existance, but
the standard allows it. [Genuine strictly conforming itoa
functions have previously been posted to clc.]

--
Peter

Nov 14 '05 #11
Peter Nilsson wrote:
CBFalconer wrote:
...
What issue? A value of LONG_MIN is immediately converted to an
unsigned long with a '-' sign emitted.


The conversion of LONG_MIN to unsigned long may yield 0.

It's not likely to on any implementation in existance, but
the standard allows it. [Genuine strictly conforming itoa
functions have previously been posted to clc.]


I see no way for a non-zero integer to be converted to zero. Show
me. Remember that ULONG_MAX has to be odd, as implied by the
imposed weighted bit construction.
--
Some informative links:
news:news.announce.newusers
http://www.geocities.com/nnqweb/
http://www.catb.org/~esr/faqs/smart-questions.html
http://www.caliburn.nl/topposting.html
http://www.netmeister.org/news/learn2quote.html
Nov 14 '05 #12
1. use lib function

#include <stdlib.h>
#include <stdio.h>

int main(void)
{
int number = 4;
char string[25];

itoa(number, string, 10);
printf("integer = %d string = %s\n", number, string);
return 0;
}

2. write a function like itoa

char* itoap(int val, int base)
{
static char buf[32] = {0};
int i = 30;
for(; val && i ; --i, val /= base){
buf[i] ="0123456789abcdef"[val % base];
printf("%c\n",buf[i]);
}
return &buf[i+1];
}

"Davey" <da***@hello.com> 写入消
息新闻:37*************@individual.net...
How do I display an integer in binary format in C?

e.g. 4 displayed as "100"

Nov 14 '05 #13
I'am sorry!
itoa(number,string,10) should be corrected to itoa(number,string,2)

"Michael" <qq*******@126.com> 写入消息新闻:cv**********@news.yaako.com...
1. use lib function

#include <stdlib.h>
#include <stdio.h>

int main(void)
{
int number = 4;
char string[25];

itoa(number, string, 10);
printf("integer = %d string = %s\n", number, string);
return 0;
}

2. write a function like itoa

char* itoap(int val, int base)
{
static char buf[32] = {0};
int i = 30;
for(; val && i ; --i, val /= base){
buf[i] ="0123456789abcdef"[val % base];
printf("%c\n",buf[i]);
}
return &buf[i+1];
}

"Davey" <da***@hello.com> 写入消
息新闻:37*************@individual.net...
How do I display an integer in binary format in C?

e.g. 4 displayed as "100"


Nov 14 '05 #14
On Tue, 22 Feb 2005 19:14:52 +0800, Michael
<qq*******@126.com> wrote:
1. use lib function

#include <stdlib.h>
#include <stdio.h>

int main(void)
{
int number = 4;
char string[25];

itoa(number, string, 10);
There is no such function in Standard C.
printf("integer = %d string = %s\n", number, string);
return 0;
}
2. write a function like itoa

char* itoap(int val, int base)
{
static char buf[32] = {0};
How do you know that 32 characters is enough? It isn't, even with 32
bit values. The correct size should be something like:

#include <limits.h>

#define MAX_DIGITS (sizeof(val) * CHAR_BIT)

then define the buffer as

static char buf[MAX_DIGITS+1] = {0};
int i = 30;
and that should initialise i to MAX_DIGITS.
for(; val && i ; --i, val /= base){
buf[i] ="0123456789abcdef"[val % base];
printf("%c\n",buf[i]);
}
return &buf[i+1];
}


Also, it would be a good idea to test base for being greater than 1 and
no greater than 16 and return some sort of error (possibly a null
pointer, possibly fill the buffer with stars, or just assert()).

Chris C
Nov 14 '05 #15
CBFalconer wrote:
Peter Nilsson wrote:
CBFalconer wrote:
...
What issue? A value of LONG_MIN is immediately converted to an
unsigned long with a '-' sign emitted.


The conversion of LONG_MIN to unsigned long may yield 0.

It's not likely to on any implementation in existance, but
the standard allows it. [Genuine strictly conforming itoa
functions have previously been posted to clc.]


I see no way for a non-zero integer to be converted to zero.
Show me. Remember that ULONG_MAX has to be odd, as implied
by the imposed weighted bit construction.


6.2.6.2p2 "...(if there are M value bits in the signed type
and N in the unsigned type, then M <= N). ..."

Thus, ULONG_MAX == LONG_MAX is allowed by the standards (other
constraints notwithstanding.) On such a machine, conversion of
LONG_MIN to unsigned long may produce 0.

--
Peter

Nov 14 '05 #16
Peter Nilsson wrote:
CBFalconer wrote:
Peter Nilsson wrote:
CBFalconer wrote:
...
What issue? A value of LONG_MIN is immediately converted to
an unsigned long with a '-' sign emitted.

The conversion of LONG_MIN to unsigned long may yield 0.

It's not likely to on any implementation in existance, but
the standard allows it. [Genuine strictly conforming itoa
functions have previously been posted to clc.]


I see no way for a non-zero integer to be converted to zero.
Show me. Remember that ULONG_MAX has to be odd, as implied
by the imposed weighted bit construction.


6.2.6.2p2 "...(if there are M value bits in the signed type
and N in the unsigned type, then M <= N). ..."

Thus, ULONG_MAX == LONG_MAX is allowed by the standards (other
constraints notwithstanding.) On such a machine, conversion of
LONG_MIN to unsigned long may produce 0.


Following from N869

[#2] For signed integer types, the bits of the object
representation shall be divided into three groups: value
bits, padding bits, and the sign bit. There need not be any
padding bits; there shall be exactly one sign bit. Each bit
that is a value bit shall have the same value as the same
bit in the object representation of the corresponding
unsigned type (if there are M value bits in the signed type
and N in the unsigned type, then M<=N). If the sign bit is
zero, it shall not affect the resulting value. If the sign
bit is one, then the value shall be modified in one of the
following ways:

-- the corresponding value with sign bit 0 is negated;

-- the sign bit has the value -2N;

-- the sign bit has the value 1-2N.

And there is a silly contradiction. The above specifies the
evaluation of the sign bit in the unsigned version. The sign bit
is NOT a value bit in the signed version. Thus there has to be an
extra bit position in the unsigned version. i.e. the <= above
should be <.

--
Some informative links:
news:news.announce.newusers
http://www.geocities.com/nnqweb/
http://www.catb.org/~esr/faqs/smart-questions.html
http://www.caliburn.nl/topposting.html
http://www.netmeister.org/news/learn2quote.html

Nov 14 '05 #17
CBFalconer <cb********@yahoo.com> writes:
[...]
Following from N869

[#2] For signed integer types, the bits of the object
representation shall be divided into three groups: value
bits, padding bits, and the sign bit. There need not be any
padding bits; there shall be exactly one sign bit. Each bit
that is a value bit shall have the same value as the same
bit in the object representation of the corresponding
unsigned type (if there are M value bits in the signed type
and N in the unsigned type, then M<=N). If the sign bit is
zero, it shall not affect the resulting value. If the sign
bit is one, then the value shall be modified in one of the
following ways:

-- the corresponding value with sign bit 0 is negated;

-- the sign bit has the value -2N;

-- the sign bit has the value 1-2N.

And there is a silly contradiction. The above specifies the
evaluation of the sign bit in the unsigned version. The sign bit
is NOT a value bit in the signed version. Thus there has to be an
extra bit position in the unsigned version. i.e. the <= above
should be <.


No, I don't think so. This only specifies the evaluation of the sign
bit in the *signed* version.

In particular, an implementation with the following characteristics
could be conforming:

CHAR_BIT == 8
sizeof(int) == 2
sizeof(unsigned int) == 2
int has 1 sign bit and 15 value bits (two's-complement)
unsigned int has 1 padding bit and 15 value bits
INT_MIN == -32768
INT_MAX == +32767
UINT_MAX == +32767

If this is non-conforming, please indicate why.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #18
Keith Thompson wrote:
<snip>
In particular, an implementation with the following characteristics
could be conforming:

CHAR_BIT == 8
sizeof(int) == 2
sizeof(unsigned int) == 2
int has 1 sign bit and 15 value bits (two's-complement)
unsigned int has 1 padding bit and 15 value bits
INT_MIN == -32768
INT_MAX == +32767
UINT_MAX == +32767

If this is non-conforming, please indicate why.


It's non-conforming because UINT_MAX must equal or exceed 65535.
Nov 14 '05 #19
CBFalconer wrote:
Peter Nilsson wrote:

6.2.6.2p2 "...(if there are M value bits in the signed type
and N in the unsigned type, then M <= N). ..."

Thus, ULONG_MAX == LONG_MAX is allowed by the standards (other
constraints notwithstanding.) On such a machine, conversion of
LONG_MIN to unsigned long may produce 0.
Following from N869

[#2] For signed integer types, the bits of the object
representation shall be divided into three groups: value
bits, padding bits, and the sign bit. There need not be any
padding bits; there shall be exactly one sign bit. Each bit
that is a value bit shall have the same value as the same
bit in the object representation of the corresponding
unsigned type (if there are M value bits in the signed type
and N in the unsigned type, then M<=N). ...


Exactly!
If the sign bit is
zero, it shall not affect the resulting value. If the sign
bit is one, then the value shall be modified in one of the
following ways:

-- the corresponding value with sign bit 0 is negated;

-- the sign bit has the value -2N;

-- the sign bit has the value 1-2N.

And there is a silly contradiction.
Only if you make the assumption that the sign bit contributes
as a value bit in the unsigned type. The standard does not
state that it does.
The above specifies the
evaluation of the sign bit in the unsigned version.
No. Only 6.2.6.2p5 states that the corresponding sign bit in
an unsigned ingteger type is required to be 0 for all non-
negative values of the signed integer type.
The sign bit is NOT a value bit in the signed version.
True!
Thus there has to be an extra bit position in the unsigned
version.
Yes, but it needn't contribute a value.
i.e. the <= above should be <.


No.

C89 has the same statement about the number of value bits,
although it doesn't _explicitly_ allow padding bits. Hence
the change in wording in C99.

The purpose of this clause is apparently to allow for
implementations that use floating point mechanics to mimic
signed and unsigned integer types.

--
Peter

Nov 14 '05 #20
Keith Thompson wrote:

... an implementation with the following characteristics
could be conforming:

CHAR_BIT == 8
sizeof(int) == 2
sizeof(unsigned int) == 2
sizeof(unsigned) must equal sizeof(int)
int has 1 sign bit and 15 value bits (two's-complement)
unsigned int has 1 padding bit and 15 value bits
INT_MIN == -32768
INT_MAX == +32767
UINT_MAX == +32767

If this is non-conforming, please indicate why.


5.2.4.2.1 Sizes of integer types <limits.h>

- [minimum] maximum value for an object of type unsigned int
UINT_MAX 65535

But if you say...

CHAR_BIT == 9
sizeof(int) == 2
int has 1 padding bit, 1 sign bit and 16 value bits
unsigned int has 2 padding bits and 16 value bits
INT_MIN == -65535
INT_MAX == +65535
UINT_MAX == +65535

....this is allowed.

--
Peter

Nov 14 '05 #21
infobahn <in******@btinternet.com> writes:
Keith Thompson wrote:

<snip>
In particular, an implementation with the following characteristics
could be conforming:

CHAR_BIT == 8
sizeof(int) == 2
sizeof(unsigned int) == 2
int has 1 sign bit and 15 value bits (two's-complement)
unsigned int has 1 padding bit and 15 value bits
INT_MIN == -32768
INT_MAX == +32767
UINT_MAX == +32767

If this is non-conforming, please indicate why.


It's non-conforming because UINT_MAX must equal or exceed 65535.


Oops. Good catch, thanks.

Amend the above to:

CHAR_BIT == 8
sizeof(int) == 4
sizeof(unsigned int) == 4
int has 1 sign bit and 31 value bits (two's-complement)
unsigned int has 1 padding bit and 31 value bits
INT_MIN == -2147483648 /* -2**31 */
INT_MAX == +2147483647 /* 2**31-1 */
UINT_MAX == +2147483647 /* 2**31-1 */

There are, of course, many other possibilities.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #22
Davey wrote:
How do I display an integer in binary format in C?

e.g. 4 displayed as "100"


Just because I can't resist:

static void outBinaryInt (unsigned int l) {
if (!l) return;
outBinaryInt (l >> 1);
putchar ("01"[l&1]);
}

void outBinary (unsigned int l) {
if (l) outBinaryInt (l);
else putchar ("0");
}

Its not fast, but it will get the job done. :)

---
Paul Hsieh
http://www.pobox.com/~qed/
http://bstring.sf.net/

Nov 14 '05 #23
CBFalconer wrote:

Peter Nilsson wrote:
Stan Milam wrote:
CBFalconer wrote:


<snip>
CB, keep it small, keep it simple, keep it readable and you
will be more productive and live longer.


Any reason why you quoted the whole thing?

Your post would be more productive if you pointed out the
issue with LONG_MIN within CBF's code. ;)


What issue? A value of LONG_MIN is immediately converted to an
unsigned long with a '-' sign emitted.


If LONG_MIN equals (-ULONG_MAX - 1), then there's the problem.
You didn't seem to understand the issue concerning INT_MIN
way back when we discussed itoa, either.

--
pete
Nov 14 '05 #24

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

4 posts views Thread by Leslaw Bieniasz | last post: by
8 posts views Thread by bearophileHUGS | last post: by
2 posts views Thread by akash deep batra | last post: by
7 posts views Thread by elliotng.ee | last post: by
3 posts views Thread by zgfareed | last post: by
1 post views Thread by girl23 | last post: by
1 post views Thread by Solo | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.