Hi Everyone. Thanks for the help with the qudratic equation problem...I
didn't think about actually doing the math...whoops. Anyway... I'm
having some trouble getting the following program to work. I want to
output a bit pattern from base 10 input. All I get is a zero after the
input...I've looked over the code but can't see the problem...any ideas?
/* display the bit pattern corresponding to
a signed decimal integer */
#include<stdio. h>
#include<stdlib .h>
int main(void)
{
int a, b, m, count, nbits;
unsigned mask;
/* determine the word size in bits and set the initial mask */
nbits = 8 * sizeof(int);
m = 0x1 << (nbits - 1); /* Place 1 in leftmost position */
/* main loop */
do {
/* read a signed integer */
printf("\n\nEnt er an integer value (0 to stop): ", a);
scanf("%d", &a);
/* output the bit pattern */
mask = m;
for(count = 1; count <= nbits; count++); {
b = (a & mask) ? 1 : 0; /* set display bit on or off */
printf("%x", b); /* print display bit */
if (count % 4 == 0)
printf(" "); /* blank space after ever 4th digit */
mask >>= 1; /* shift mask 1 position to the right */
}
} while (a != 0);
return EXIT_SUCCESS; /* If it's there why not use it people! */
}
Nov 14 '05
47 5292
Mac wrote: mask >>= 1; /* shift mask 1 position to the right */
I don't think the above line will do what you expect.
Nice try invoking UD on signed shift, but mask is unsigned. It was
merely assigned from a signed variable, but I think that's well-defined
with two's-complement semantics. As an aside, in my experience, even
signed variable shifts typically get compiled into logical rather than
arithmetic shifts.
--
Derrick Coetzee
I grant this newsgroup posting into the public domain. I disclaim all
express or implied warranty and all liability. I am not a professional.
"fb" <fb@goaway.ne t> wrote in message
news:LAuZc.2995 40$gE.33632@pd7 tw3no... Hi Everyone. Thanks for the help with the qudratic equation
problem...I didn't think about actually doing the math...whoops.
It's actually a very, very big oops that I hope you learn from
and don't just hand wave it.
Computers are really, really stupid. They crunch numbers - and
that's about it. It is up to YOU to solve the problem. Before you
start coding you should try some hand cases and crank the math
and you should especially do that as soon as a problem arises.
There seems to be an ever increasing trend towards just wanting
to throw code at the compiler without understanding what that
code does or is even supposed to do. Don't let yourself fall into
that trap.
Anyway... I'm having some trouble getting the following program to work. I
want to output a bit pattern from base 10 input. All I get is a zero
after the input...I've looked over the code but can't see the
problem...any ideas?
All you get is "a zero"? As in a single zero? Even though you
have a loop that is guaranteed to print out something every time
through it? What does that tell you? Either the test only passes
the first time through, or the loop code isn't the code you think
it is. If examining the code with this in mind doesn't tell you
something, then instrument the loop by printing out the value of
count within the body of the loop. If it prints out "1" then the
loop is only executing once - look for something in the loop that
is changing one of the values in the test expression. If it
prints out a "9" then what you thought was the loop is not
actually part of the loop. There's a REAL common mistake that can
result in that - so learning how to track it down through
systematic debugging when the Mark II eyeballs insist on skipping
over it (which that are want to do because, as a human with a
functioning human brain, you automatically tend to see what you
WANT the code to be instead of what the code actually IS) can be
a very valuable lesson. I'll leave it for you to track down this
problem further.
You have another potential problem in that any time you do right
shift operations on signed integers, you don't know for sure what
it going to get shifted in to the vacated bit position. You also
don't know for sure how negative values are represented - but
that's sort of the point of the exercise, isn't it?
This is my take on performing any kind of bit banging - the folks
that wrote C intended it to be primarily a high level language
where the programmer worked with "values" and not
"representation s". They therefore primarily define how the
different operations behave with respect to the values being
represented and not the representations themselves. They leave it
up to the compiler designer to make that happen and leave them
free to play whatever games they like to (subject to a few
constraints) with the internal representations . But, they
recognize that a few people will have the need/desire to do bit
banging and so they defined a minimal set of operations that have
to have completely well-defined effects on the internal
representation - but imposing this constraint imposes unnecessary
limitations on the games the compiler writer can play in working
with the "values", so the ONLY data type (as far as I know) that
they included in this tightly constrained bit-level definition
are the unsigned integers. Not the integers, only the unsigned
integers. Therefore, only bit bang unsigned integers. /* display the bit pattern corresponding to a signed decimal integer */
#include<stdio. h> #include<stdlib .h>
int main(void) { int a, b, m, count, nbits; unsigned mask;
/* determine the word size in bits and set the initial mask
*/ nbits = 8 * sizeof(int); m = 0x1 << (nbits - 1); /* Place 1 in leftmost position */
/* main loop */ do { /* read a signed integer */ printf("\n\nEnt er an integer value (0 to stop): ", a); scanf("%d", &a);
/* output the bit pattern */ mask = m; for(count = 1; count <= nbits; count++); { b = (a & mask) ? 1 : 0; /* set display bit on or off */ printf("%x", b); /* print display bit */ if (count % 4 == 0) printf(" "); /* blank space after ever 4th digit */ mask >>= 1; /* shift mask 1 position to the right */ } } while (a != 0); return EXIT_SUCCESS; /* If it's there why not use it
people! */ }
"fb" <fb@goaway.ne t> wrote in message
news:dRvZc.2857 14$M95.236771@p d7tw1no...
Derrick Coetzee wrote:
fb wrote:
nbits = 8 * sizeof(int);
The error is on this line.
right-o thanks.
So....that told you what the problem is?
Watch out - you're hand waving it. I get the impression you
aren't trying to understand what the problem is, you are just
wanting someone to tell you what code to throw at the compiler.
Otherwise you should have asked what could possibly be wrong with
that line. It should work for you - but it is not robust and,
conceivably, might not work on your machine - and even if it did
have a problem it wouldn't yield the result you are experiencing.
But I'm not getting the impression that understanding the
relationship between your code and the results your code produce
is very high on your priority list.
"Derrick Coetzee" <dc****@moonfla re.com> wrote in message
news:ch******** **@news-int2.gatech.edu ... Mac wrote:
mask >>= 1; /* shift mask 1 position to the right */ I don't think the above line will do what you expect.
Nice try invoking UD on signed shift, but mask is unsigned. It
was merely assigned from a signed variable, but I think that's
well-defined with two's-complement semantics.
But what is the basis for assuming two's complement semantics?
Even if it is, let's say that I have a four bit two's complement
value represented as 1000 stored in a signed variable m. What
value is that? What value will get stored in the four bit
unsigned variable n if I use n=m ?
As assignments between signed and unsigned data types of the same
basic type required to copy the bit pattern if the value in the
expression can't be represented in the type of the object being
assigned to? Or is this undefined behavior?
As an aside, in my experience, even signed variable shifts typically get compiled into logical
rather than arithmetic shifts.
That's been the exact opposite of mine. For instance, the
following code:
#include <stdio.h>
int main(void)
{
int i;
i = -8;
printf("%i %i\n", i, i >> 1);
return 0;
}
printed:
-8 -4
(Using Borland TurboC/C++ v4.5)
William L. Bahn wrote: As assignments between signed and unsigned data types of the same basic type required to copy the bit pattern if the value in the expression can't be represented in the type of the object being assigned to? Or is this undefined behavior?
Assigning an out of range value to a signed integer,
is implementation defined.
To assign a negative value to an unsigned,
(UINT_MAX + 1) is added to the value until it becomes non negative.
To assign an out of range positive value to an unsigned,
(UINT_MAX + 1) is subtracted until the value is in range.
--
pete
fb wrote: I want to output a bit pattern from base 10 input.
/* display the bit pattern corresponding to
a signed decimal integer */
#include<stdio. h>
#include<stdlib .h>
#include<limits .h>
#define LENGTH 80
#define str(x) # x
#define xstr(x) str(x)
void bitstr(char *, void const *, size_t);
int main(void)
{
int a, rc;
char abits[CHAR_BIT * sizeof a + 1], string[LENGTH + 1];
fputs("\n\nEnte r an integer value (0 to stop): ", stdout);
fflush(stdout);
rc = scanf("%" xstr(LENGTH) "[^\n]%*[^\n]", string);
if (!feof(stdin)) {
getchar();
}
while (rc == 1) {
a = atoi(string);
bitstr(abits, &a, sizeof a);
printf(" %s = %d\n", abits, a);
if (a == 0) {
break;
}
fputs("\n\nEnte r an integer value (0 to stop): ", stdout);
fflush(stdout);
rc = scanf("%" xstr(LENGTH) "[^\n]%*[^\n]", string);
if (!feof(stdin)) {
getchar();
}
}
return 0;
}
void bitstr(char *str, const void *obj, size_t n)
{
unsigned mask;
const unsigned char *byte = obj;
while (n--) {
mask = ((unsigned char)-1 >> 1) + 1;
do {
*str++ = (char)(mask & byte[n] ? '1' : '0');
mask >>= 1;
} while (mask != 0);
}
*str = '\0';
}
--
pete
"pete" <pf*****@mindsp ring.com> wrote in message
news:41******** ***@mindspring. com... William L. Bahn wrote:
As assignments between signed and unsigned data types of the same basic type required to copy the bit pattern if the value in the expression can't be represented in the type of the object being assigned to? Or is this undefined behavior? Assigning an out of range value to a signed integer, is implementation defined. To assign a negative value to an unsigned, (UINT_MAX + 1) is added to the value until it becomes non negative.
(or, obviously, ULONG_MAX + 1 etc, according to the type of the object being
assigned to.)
....which, if the negative value can be represented using two's complement in
the number of value bits in the unsigned integer, leaves the unsigned
integer with the two's complement representation of the negative value.
In many cases this means that assignment of a signed integer type to the
corresponding unsigned integer type does indeed simply copy the bit pattern.
To assign an out of range positive value to an unsigned, (UINT_MAX + 1) is subtracted until the value is in range.
Alex
Gordon Burditt wrote: /* read a signed integer */ printf("\n\nEnt er an integer value (0 to stop): ", a); ^^^ What is this? You also need a "fflush(stdin); " after this.
No, you absolutely NEVER need a "fflush(stdin)" . If you absolutely have to invoke undefined behavior, use fflush(void main()). It will probably save you a lot of time by failing to compile.
Did I actually write stdin? Must be the cat on the keyboard.
Obviously I meant stdout. Thanks for the correction.
--
A: Because it fouls the order in which people normally read text.
Q: Why is top-posting such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
On Thu, 02 Sep 2004 01:21:47 GMT, fb <fb@goaway.ne t> wrote: Hi Everyone. Thanks for the help with the qudratic equation problem...I didn't think about actually doing the math...whoops. Anyway... I'm having some trouble getting the following program to work. I want to output a bit pattern from base 10 input. All I get is a zero after the input...I've looked over the code but can't see the problem...any ideas?
/* display the bit pattern corresponding to a signed decimal integer */
#include<stdio .h> #include<stdli b.h>
int main(void) { int a, b, m, count, nbits; unsigned mask;
/* determine the word size in bits and set the initial mask */ nbits = 8 * sizeof(int); m = 0x1 << (nbits - 1); /* Place 1 in leftmost position */
/* main loop */ do { /* read a signed integer */ printf("\n\nEnt er an integer value (0 to stop): ", a);
a is uninitialized. You cannot pass it to a function in this state,
even if the function will not attempt to evaluate it. This invokes
undefined behavior. In this case, you probably don't want to pass it
at all anyway.
snip
<<Remove the del for email>>
On Thu, 02 Sep 2004 09:41:24 GMT, pete <pf*****@mindsp ring.com> wrote: William L. Bahn wrote:
As assignments between signed and unsigned data types of the same basic type required to copy the bit pattern if the value in the expression can't be represented in the type of the object being assigned to? Or is this undefined behavior? Assigning an out of range value to a signed integer, is implementation defined.
No, it is undefined.
To assign a negative value to an unsigned, (UINT_MAX + 1) is added to the value until it becomes non negative. To assign an out of range positive value to an unsigned, (UINT_MAX + 1) is subtracted until the value is in range.
<<Remove the del for email>> This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Christian Stork |
last post by:
Hello everybody,
I am using Python to prototype a compression algorithm for tree-shaped
data, e.g., XML data or abstract syntax trees. I use a variant of the
visitor design pattern--called weaver/yarn pattern--in order to
traverse the tree that is being compressed or decompressed. I do not
know of any other interesting application of the weaver/yarn pattern,
but it seems like a very suitable subject of study for different...
|
by: Andy Read |
last post by:
Hello all,
I have the requirement to produce source code that produces an object
hierarchy.
Example:
Root
|
Folder 1
|
by: Medi Montaseri |
last post by:
Hi,
Given a collection of similar but not exact entities (or products)
Toyota, Ford, Buick, etc; I am contemplating using the Abstraction pattern
to provide a common interface to these products. So I shall have an
Abstract Base called 'Car' implemented by Toyota, Ford, and Buick.
Further I'd like to enable to client to say
Car *factory;
|
by: Omer van Kloeten |
last post by:
The Top Level Design:
The class Base is a factory class with a twist. It uses the Assembly/Type
classes to extract all types that inherit from it and add them to the list
of types that inherit from it. During run time, using a static method, the
class creates an instance of the derived class using the Activator class and
returns it. This design pattern is very similar to the design pattern
applied by the Assembly class.
The twist is...
|
by: shonend |
last post by:
I am trying to extract the pattern like this :
"SUB: some text LOT: one-word"
Described, "SUB" and "LOT" are key words; I want those words,
everything in between and one word following the "LOT:". Source text
may contain multiple "SUB: ... LOT:" blocks.
For example this is my source text:
| |
by: Krivenok Dmitry |
last post by:
Hello All!
I am trying to implement my own Design Patterns Library.
I have read the following documentation about Observer Pattern:
1) Design Patterns by GoF
Classic description of Observer. Also describes implementation
via ChangeManager (Mediator + Singleton)
2) Pattern hatching by John Vlissides
Describes Observer's implementation via Visitor Design Pattern.
3) Design Patterns Explained by Alan Shalloway and James Trott
|
by: konrad Krupa |
last post by:
I'm not expert in Pattern Matching and it would take me a while to come up
with the syntax for what I'm trying to do.
I hope there are some experts that can help me.
I'm trying to match /d/d/d/s/d/d in any text.
There could be spaces in front or after the pattern (the nnn nn could be
without spaces also) but it shouldn't pick it up in case like this
1234 56768
|
by: =?Utf-8?B?QWFyb24=?= |
last post by:
Hi,
I'm having a tricky problem where I want to accept a regular expression
pattern from user input but can't get teh escape characters to be prcoessed
correctly. If I take the same pattern and declare it in code with a
preceeding @ character it works fine.
To get the pattern to work from teh suer all \ have to be escaped, e.g.
instead of \d a user would have to enter \\d.
|
by: George Sakkis |
last post by:
I have a situation where one class can be customized with several
orthogonal options. Currently this is implemented with (multiple)
inheritance but this leads to combinatorial explosion of subclasses as
more orthogonal features are added. Naturally, the decorator pattern
comes to mind (not to be confused with the the Python meaning of
the term "decorator").
However, there is a twist. In the standard decorator pattern, the
decorator...
|
by: Slaunger |
last post by:
Hi all,
I am a Python novice, and I have run into a problem in a project I am
working on, which boils down to identifying the patterns in a sequence
of integers, for example
..... 1 6 6 1 6 6 1 6 6 1 6 6 1 6 6 1 9 3 3 0 3 3 0 3 3 0 3 3 0 10 6 6
1 6 6 1 6 6 1 6 6 1 6 6 1 6 6 1 6 6 1 9 3 3 0 3 3 0 3 3 0 3 3 0 10 6 6
1 6 6 1 6 6 1 6 6 1 6 6 1 6 6 1 6 6 1 9 3 3 0 3 3 0 3 3 0 3 3 0 10 6 6
1 6 6 1 6 6 1 6 6 1 6 6 1 6 6 1 6 6 1 9 3 3 0 3 3 0...
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
| |
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
| |
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |