473,804 Members | 3,460 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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().
--
"combinatio n is the heart of chess"

A.Alekhine

Mail to:
sathyashrayan AT gmail DOT com


Nov 14 '05 #1
5 2929
In article <42************ *********@authe n.white.readfre enews.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.


--
"combinatio n 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, "sathyashra yan"
<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?
--
"combinatio n is the heart of chess"

A.Alekhine

Mail to:
sathyashrayan AT gmail DOT com

Nov 14 '05 #5
In article <42************ ***********@aut hen.white.readf reenews.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
2052
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 is a 128-byte header and the rest of the file is integers in 2-byte format. What I want to do is to save the binary data into several smaller files
5
7067
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: "9567081354794432" should be converted to the seven bytes: 0x21FD35B5B095C0 Thanks in advance Sam
5
17334
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 word/name into ASCII decimal for each character you type on the ...'black screen?' (dont know what to call it but i mean the screen that appears when you press F5). I found a file (i think somewhere on this site?) that would change a string of characters...
6
2038
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 convert that to decimal I would get 12154. I can't figure out how to concatenate? my hex values together if that makes any sense? Any pointers would be greatly appreciated!
1
1826
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 screwed up because this doesn't work as expected. Can cookies store any non-ascii characters? (I'm thinking that maybe this limitation is what is screwing me up). Thanks, (I've confirmed that the 2-way encryption using the following routine...
7
19240
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 00000000000000001111111111111111 11111111111111111111111111111111 00000000000000000000000000000000 11111111111111110000000000000000
1
2605
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 ascii of (00.00.11.00.00.02) .. ........ Likewise I read the mac entries from the text file using a perl script and do some processing
9
4150
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. What am I doing wrong? Dim plainText As String plainText = "t═e" Dim plainTextBytes() As Byte Dim enc As Encoding = Encoding.ASCII plainTextBytes = enc.GetBytes(plainText)
5
2592
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 it in my own class it gives me alot of headache, also because I'm totally new to the language. It work only with one character at a time, and if I give a string it just give some weird result.
0
9711
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look ! Part I. Meaning of...
0
10594
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10343
jinu1996
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...
1
10331
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10087
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 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...
0
6861
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();...
0
5667
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3831
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3001
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.