473,396 Members | 1,655 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

ascii binary string into an integer

Group,
I have some doubts in the following program.

------------------program---------------------
/*
** Make an ascii binary string into an integer.
*/

#include <string.h>
unsigned int bstr_i(char *cptr)
{
unsigned int i, j = 0;
while (cptr && *cptr && strchr("01", *cptr))
{
i = *cptr++ - '0';
j <<= 1;
j |= (i & 0x01);
}
return(j);
}
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char *arg;
unsigned int x;
while (--argc)
{
x = bstr_i(arg = *++argv);
printf("Binary %s = %d = %04Xh\n", arg, x, x);
}
return EXIT_SUCCESS;
}
-----------------------------------------------------------

My doubts are:
1)In the expression
i = *cptr++ - '0';
the pointer cptr is dereffered and subtracted with the char constant
'0'. As far as I know, the above expression will return the number of chars
in-between cptr and '0'. Then the variable i will either 1 or 0.
Am I correct or wrong?

2)What is the meaning of "Make an ASCII binary string into an integer."
Any web reference or a link for the above.

3)What ever number I input I get the answer 0000h except when I input 1
by that I will get 0001h. Why is that?

In short I am very much confused by the above program. Can any one take
some time in explaining the while block in the function bstr_i().
--
"combination is the heart of chess"

A.Alekhine

Mail to:
sathyashrayan AT gmail DOT com


Nov 14 '05 #1
5 2902
In article <42*********************@authen.white.readfreenews .net>,
sathyashrayan <sa***********@REMOVETHISgmail.com> wrote:
My doubts are:
1)In the expression
i = *cptr++ - '0';
the pointer cptr is dereffered and subtracted with the char constant
'0'. As far as I know, the above expression will return the number of chars
in-between cptr and '0'. Then the variable i will either 1 or 0.
Am I correct or wrong?
Incorrect.

Derefferencing a char* gets you a char, so you are doing the
difference between a char and a different char. If the first
char falls in the range '0' through '9' then the subtraction
yields the decimal value that is represented for printing purposes
by the char (e.g., value 2 if the char is '2'.)
3)What ever number I input I get the answer 0000h except when I input 1
by that I will get 0001h. Why is that?


Try entering something like 101 and seeing what the answer is.
If you experiment with that and 1000 and 11111111 then you
will likely quickly discovere the answer to your second
question.
--
Look out, there are llamas!
Nov 14 '05 #2
sathyashrayan wrote:
Group,
I have some doubts in the following program.

------------------program---------------------
/*
** Make an ascii binary string into an integer.
*/

#include <string.h>
unsigned int bstr_i(char *cptr)
{
unsigned int i, j = 0;
while (cptr && *cptr && strchr("01", *cptr))
{
i = *cptr++ - '0';
j <<= 1;
j |= (i & 0x01);
}
return(j);
}
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char *arg;
unsigned int x;
while (--argc)
{
x = bstr_i(arg = *++argv);
printf("Binary %s = %d = %04Xh\n", arg, x, x);
}
return EXIT_SUCCESS;
}
-----------------------------------------------------------

My doubts are:
1)In the expression
i = *cptr++ - '0';
the pointer cptr is dereffered and subtracted with the char constant
'0'. As far as I know, the above expression will return the number of chars
in-between cptr and '0'. Then the variable i will either 1 or 0.
Am I correct or wrong?
You're correct. *cptr is either '0' or '1' (value 48 or 49) and the
constant '0' (which is 48) is then subtracted giving either 0 or 1.

The value of cptr is also incremented to point to the next 'char' in memory.

2)What is the meaning of "Make an ASCII binary string into an integer."
Any web reference or a link for the above.
Think about (1).

Hint, understand the meaning of a string. It's a sequence of data,
terminated by a special character.

In the context of C, it's a sequence of bytes that are in the range
defined by the ASCII standard, terminated by NUL.

3)What ever number I input I get the answer 0000h except when I input 1
by that I will get 0001h. Why is that?
Again, think about (1). Make sure you understand precisely what the
input is (and it's a string) and what the output is.

What's a binary number? This is the basis for computers at a transistor
level.

What does 10 give? I would imagine it returns 0002h.

In short I am very much confused by the above program. Can any one take
some time in explaining the while block in the function bstr_i().
Sorry if I asked more questions than you did, but this should give you a
good starting point in researching the meaning of the program.


--
"combination is the heart of chess"

A.Alekhine

Mail to:
sathyashrayan AT gmail DOT com

Nov 14 '05 #3
On Wed, 13 Apr 2005 14:01:18 +0530, "sathyashrayan"
<sa***********@REMOVETHISgmail.com> wrote:
Group,
I have some doubts in the following program.

------------------program---------------------
/*
** Make an ascii binary string into an integer.
*/

#include <string.h>
unsigned int bstr_i(char *cptr)
{
unsigned int i, j = 0;
while (cptr && *cptr && strchr("01", *cptr))
The first expression confirms that cptr is not NULL. This is
"necessary" so that the next expression does not invoke undefined
behavior.

The second expression confirms that *cptr is not the '\0' that
terminates the string (cptr is not past the last valid character in
the string). This is necessary because if *cptr is '\0' then strchr
will never return NULL.

The third expression confirms that *cptr is either a 0 or 1. If *cptr
is not '0' or '1', strchr will return NULL.

The loop repeats until one of the three expressions evaluates to NULL
or '\0', which will be treated as false.
{
At this point, you know that *cptr must be '0' or '1'.
i = *cptr++ - '0';
Consequently, i must be 0 or 1.
j <<= 1;
j |= (i & 0x01);
Since i must be 0 or 1, anding it with 0x01 cannot change it. j |= i
or j += i is just as effective and easier on the eyes.

In many cases, to be consistent with bases that are not powers of two,
these two statements are written as
j = j*BASE + i;
where BASE is 2 in this case.
}
return(j);
}
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char *arg;
unsigned int x;
while (--argc)
Can argc ever be 0? Probably not on any system this code is likely to
run on.
{
x = bstr_i(arg = *++argv);
printf("Binary %s = %d = %04Xh\n", arg, x, x);
%d expects an int. x is an unsigned int. Better to use %u.
}
return EXIT_SUCCESS;
}
-----------------------------------------------------------

My doubts are:
snip
2)What is the meaning of "Make an ASCII binary string into an integer."
Any web reference or a link for the above.
Whatever the inventor of the exercise wanted it to mean. You seem to
have interpreted it the same way I did.

3)What ever number I input I get the answer 0000h except when I input 1
by that I will get 0001h. Why is that?
I ran your code and got the expected results. Are your values such
that the last four hex digits are always 0?

In short I am very much confused by the above program. Can any one take
some time in explaining the while block in the function bstr_i().


See above

<<Remove the del for email>>
Nov 14 '05 #4
The code is not mine. I took it from C snippet archives. I searches
for the word "ascii binary string into an integer" in google. I have so
far got this bellow given code from the snippet archive itself.
Group,
I have some doubts in the following program.

------------------program---------------------
/*
** Make an ascii binary string into an integer.
*/

#include <string.h>
unsigned int bstr_i(char *cptr)
{
unsigned int i, j = 0;
while (cptr && *cptr && strchr("01", *cptr))
The first expression confirms that cptr is not NULL. This is
"necessary" so that the next expression does not invoke undefined
behavior.

The second expression confirms that *cptr is not the '\0' that
terminates the string (cptr is not past the last valid character in
the string). This is necessary because if *cptr is '\0' then strchr
will never return NULL.

The third expression confirms that *cptr is either a 0 or 1. If *cptr
is not '0' or '1', strchr will return NULL.

The loop repeats until one of the three expressions evaluates to NULL
or '\0', which will be treated as false.
{


At this point, you know that *cptr must be '0' or '1'.
i = *cptr++ - '0';


Consequently, i must be 0 or 1.
j <<= 1;
j |= (i & 0x01);


Since i must be 0 or 1, anding it with 0x01 cannot change it. j |= i
or j += i is just as effective and easier on the eyes.


The point of my confussion. I got clared with your explanation. The variouble
i is either 0 or 1 according the while loop. So ANDin the i with 0x01 is useless.
Is that what you wanted to say.Correct? (Sorry.I lack in understanding the high
level discussions)

In many cases, to be consistent with bases that are not powers of two,
these two statements are written as
j = j*BASE + i;
where BASE is 2 in this case.
}
return(j);
}
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char *arg;
unsigned int x;
while (--argc)


Can argc ever be 0? Probably not on any system this code is likely to
run on.
{
x = bstr_i(arg = *++argv);
printf("Binary %s = %d = %04Xh\n", arg, x, x);


%d expects an int. x is an unsigned int. Better to use %u.
}
return EXIT_SUCCESS;
}
-----------------------------------------------------------

My doubts are:


snip
2)What is the meaning of "Make an ASCII binary string into an integer."
Any web reference or a link for the above.


Whatever the inventor of the exercise wanted it to mean. You seem to
have interpreted it the same way I did.

3)What ever number I input I get the answer 0000h except when I input 1
by that I will get 0001h. Why is that?


I ran your code and got the expected results. Are your values such
that the last four hex digits are always 0?


input output
10 Binary 10 = 1 = 0001h
100 Binary 100 = 3 = 0003h

Any other value outputs zero.

In short I am very much confused by the above program. Can any one take
some time in explaining the while block in the function bstr_i().


See above

<<Remove the del for email>>


Extra: Answer to my first question:

Walter Roberson in this replay thread saying that it is wrong. But
Jason Curl says it is correct. This group will correct who ever gives
a wrong, irrelevant answer. But it this case there is silence. Why?
--
"combination is the heart of chess"

A.Alekhine

Mail to:
sathyashrayan AT gmail DOT com

Nov 14 '05 #5
In article <42***********************@authen.white.readfreene ws.net>,
sathyashrayan <sa***********@REMOVETHISgmail.com> wrote:
Extra: Answer to my first question: Walter Roberson in this replay thread saying that it is wrong. But
Jason Curl says it is correct. This group will correct who ever gives
a wrong, irrelevant answer. But it this case there is silence. Why?


Your explanation was not right.

You said that a pointer was dereferenced and '0' was subtracted.
The way you phrased it implied that '0' was subtracted from the
pointer, rather than from the value at the location pointed to.
'0' is an integer (with value 48), so subtracting '0' from
a char pointer would give the location 48 characters before,
which in this case is not even likely to be in the same object.

You continued on to say that the subtraction gave the number
of characters between cptr and '0'. '0' is a character (that is,
an integer), not a pointer, so the number of characters between
cptr and '0' is not defined. And it's not what the code does anyhow:
the code gives the numeric difference between what cptr *points to*
and the integer value represented by '0', not between cptr *itself*
and something.

The "number of characters" between two characters would imply to
me that the order of the two characters was not relevant for
the comparison -- e.g., I would say that the number of
characters "between" 'A' and 'E' is the same as the number of
characters "between" 'E' and 'A'. That's not the value that
subtraction of characters gives you, though: 'E' - 'A' is
positive and easily defined, but 'A' - 'E' is logically negative
and I would have to look up the rules for subtraction when
unsigned quantities are involved. Thus, I would not normally phrase
a character subtraction as the number of characters between the two.
It wasn't the code that was incorrect, it was the way you explained
it. Some of what you said could possibly be explained as a language
difference, but when you are working with C, there are big differences
between cptr and *cptr, so you need to be careful to add in the right
operators.

--
Oh, to be a Blobel!
Nov 14 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Albert Tu | last post by:
Hi, I am learning and pretty new to Python and I hope your guys can give me a quick start. I have an about 1G-byte binary file from a flat panel x-ray detector; I know at the beggining there...
5
by: Sam Smith | last post by:
Hi, is there a function or a "well-known" algorithm which converts a number of random length represented as an array of bytes to its binary format? For example: a 16 byte long array:...
5
by: b.stewart | last post by:
I have only been using C++ for a few afternoons and i still get confused at nearly every line i type so maybe someone here can help me. Im trying to write a small program that can change a...
6
by: Willem | last post by:
What is the best way to calculate an ascii string into an integer (not talking about an atoi conversion): For examle if I have the ascii string: "/b" then in hex it would be 2F7A and if I...
1
by: Paul W | last post by:
Hi - I'm doing simple XOR encryption on a password before storing it in a cookie. I use the same 2-way encryption/decryption routine at each end (before writing/after reading). Something is getting...
7
by: elliotng.ee | last post by:
I have a text file that contains a header 32-bit binary. For example, the text file could be: %%This is the input text %%test.txt Date: Tue Dec 26 14:03:35 2006...
1
by: Vic | last post by:
I have a c program which writes mac address entries onto a text file. Text file when opened in vim looks like this index mac 1 ^@^@^Q^@^@^A ascii of (00.00.11.00.00.01) 2 ^@^@^Q^@^@^B...
9
by: =?Utf-8?B?RGFu?= | last post by:
I have the following code section that I thought would strip out all the non-ascii characters from a string after decoding it. Unfortunately the non-ascii characters are still in the string....
5
by: Canned | last post by:
Hi, I'm trying to write a class that can convert ascii to binary and vice versa. I write my class based on this function I've found on internet That works perfectly, but when I try to implement...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
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,...
0
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...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
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...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.