473,387 Members | 1,582 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,387 software developers and data experts.

Binary BitString to Int32 : Bit fiddlers only! Can you improve this?

Hi,

This programs converts a BitString "0101110" to an Int32 value.
Can anyone improve, or possibly shorten the following program?

public static int BitStringToInt32(String s)
{
int j, k, m = 0;
int len = s.Length - 1;

for (int i = 0; i <= len; i++)
{
j = 1;
k = (s[i] - '0');

if ((k 1) || (k < 0))
{
throw new System.IO.InvalidDataException("Invalid input. Must be 0 or
1");
}

j = j << (len - i);
m = m + k * j;
}

return m;
}

Thanks
Russell Mangel
Las Vegas, NV
Jul 21 '07 #1
10 1785
"Russell Mangel" <ru*****@tymer.netwrote:
Can anyone improve, or possibly shorten the following program?
public static int BitStringToInt32(String s)
{
return Convert.ToInt32(s, 2);
}

Eq.
Jul 21 '07 #2
Russell Mangel <ru*****@tymer.netwrote:
This programs converts a BitString "0101110" to an Int32 value.
Can anyone improve, or possibly shorten the following program?
Sure:

Convert.ToInt32(s, 2);

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Jul 21 '07 #3
Russell Mangel wrote:
Hi,

This programs converts a BitString "0101110" to an Int32 value.
Can anyone improve, or possibly shorten the following program?

public static int BitStringToInt32(String s)
{
int j, k, m = 0;
int len = s.Length - 1;

for (int i = 0; i <= len; i++)
{
j = 1;
k = (s[i] - '0');

if ((k 1) || (k < 0))
{
throw new System.IO.InvalidDataException("Invalid input. Must be 0 or
1");
}

j = j << (len - i);
m = m + k * j;
}

return m;
}

Thanks
Russell Mangel
Las Vegas, NV
Disregarding the obvious use of Convert, perhaps this is rather what you
were expecting?

public static int BitStringToInt32(String s) {
int result = 0;
foreach (char c in s) {
if (c != '0' && c != '1') {
throw new ArgumentException("Invalid input. Must be 0 or 1.");
}
result <<= 1;
result += c & 1;
}
return result;
}

--
Göran Andersson
_____
http://www.guffa.com
Jul 21 '07 #4
On Sun, 22 Jul 2007 03:56:48 -0700, Gaz <a@b.comwrote:
I would say it depends on how the compiler will optimize your code.
Well, if you want to get that pedantic about it (and apparently you do :)
), it also depends on how the CPU will optimize the code.
To me the first version looks more efficient.
Unless you're a compiler, I'm not sure that's a useful metric. :)
You don't want any conditional
branch statements in the assembler code if you can help it, branching is
expensive in assembler (resets the pipeline).
Branching in and of itself does not "reset the pipeline". Between having
multiple pipelines and branch prediction, simple branching by itself is
not necessarily a problem at all.

Beyond that, there's not really any difference with respect to branching
between the two versions. The compiler can optimize either into an
assumed "straight-through" case if it wants to. Though, the last time I
looked at this sort of optimization (granted, years ago), the "assumed"
case was the "true" if() statement, which means that in the former, the
optimized version will optimize for the failure case. Probably not the
best thing to do.

Besides, as far as "conditional branch statements" go, both versions have
the same nominal number of conditionals. The main difference is that the
latter version takes advantage of information generated by them to avoid
later computations. Avoiding unnecessary computations is a fundamental
technique in optimization.

(There is, of course, some chance that the compiler would notice the
opportunity to remove the unnecessary computations. But that would depend
on it having specific knowledge of the char to int conversion and relating
that to the constraint of the possible values of c by the time it gets to
the computation. I would be pretty surprised if it did pick up on that,
even as good as optimizing compilers are these days).

Of course, if the performance of this method is so critical it's worth
anywhere close to the scrutiny it's receiving here, the real issue is to
figure out why an application spends so much time converting strings to
their binary equivalent. :)

Pete
Jul 22 '07 #5
Thanks for your reply. I missed that overload for Convert.
I wonder how it will perform.
Russ

"Paul E Collins" <fi******************@CL4.orgwrote in message
news:Jp******************************@bt.com...
"Russell Mangel" <ru*****@tymer.netwrote:
>Can anyone improve, or possibly shorten the following program?

public static int BitStringToInt32(String s)
{
return Convert.ToInt32(s, 2);
}

Eq.


Jul 23 '07 #6
Thanks for your reply. I missing that overload for Convert.

I see that both you and Paul replied at almost the same time.

Russ.

"Jon Skeet [C# MVP]" <sk***@pobox.comwrote in message
news:MP*********************@msnews.microsoft.com. ..
Russell Mangel <ru*****@tymer.netwrote:
>This programs converts a BitString "0101110" to an Int32 value.
Can anyone improve, or possibly shorten the following program?

Sure:

Convert.ToInt32(s, 2);

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too

Jul 23 '07 #7

"Peter Duniho" <Np*********@nnowslpianmk.comwrote in message
news:op***************@petes-computer.local...
On Sun, 22 Jul 2007 03:56:48 -0700, Gaz <a@b.comwrote:

Of course, if the performance of this method is so critical it's worth
anywhere close to the scrutiny it's receiving here, the real issue is to
figure out why an application spends so much time converting strings to
their binary equivalent. :)

Pete
Excellent observation, it is nice to see that you are capable of optimizing
code, but only if it makes sense to do so. As you stated, converting strings
to Int32 values in production code would be inefficient.

Russell
Jul 23 '07 #8
Thanks to all who replied.

Thanks to Göran for the optimization. (See I even got the ö right.)
Thanks to Peter for optimizing Göran's version.

Russell Mangel
Las Vegas, NV
Jul 23 '07 #9
Peter Duniho wrote:
Branching in and of itself does not "reset the pipeline". Between
having multiple pipelines and branch prediction, simple branching by
itself is not necessarily a problem at all.

Beyond that, there's not really any difference with respect to branching
between the two versions. The compiler can optimize either into an
assumed "straight-through" case if it wants to. Though, the last time I
looked at this sort of optimization (granted, years ago), the "assumed"
case was the "true" if() statement, which means that in the former, the
optimized version will optimize for the failure case. Probably not the
best thing to do.

Besides, as far as "conditional branch statements" go, both versions
have the same nominal number of conditionals. The main difference is
that the latter version takes advantage of information generated by them
to avoid later computations. Avoiding unnecessary computations is a
fundamental technique in optimization.
And how does that analysis explain that the latter version is
actually slower ?

Arne
Jul 30 '07 #10
Russell Mangel wrote:
Thanks to Göran for the optimization. (See I even got the ö right.)
Thanks to Peter for optimizing Göran's version.
Before you consider something an optimization, then I suggest
that you make a little test to verify ...

Arne
Jul 30 '07 #11

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

Similar topics

3
by: cody | last post by:
Is there any built in functionality in the .NET framework to get the binary represention in form of string from a given integer? I can do 1344.ToString("x2") to get hexadecimal output but I need...
11
by: Charles T. | last post by:
Hi, I currently writing a serialize/unserialize architecture. The read/write function will read/write from a binary file. My question is is there some sort on defined standart to use when...
19
by: jeff | last post by:
how do you convert form byte to Int32 while retaining the binary value of the byte array
2
by: wwj | last post by:
hello,everyone.I am a new one here.I want to know how to define a bitstring type in c/c++? and can specify its length.Then I can use it like: bitstring a='100111' ;or so. thank you very much
3
by: Usenet User | last post by:
I am trying to read (and then save) a binary file which has certain data structures in it. (The file is in propritetary format produced by a 3rd party MFC application.) I know that those data...
15
by: Jacques | last post by:
Hi I am an dotNet newby, so pardon my ignorance. I am looking for a method of saving/copying a managed class to a stream/file WITHOUT saving the object's state, eg. if I have a ref class with...
2
by: mpreisdorf | last post by:
I want to save the raw data of a class (without the .NET object overhead) to a binary file. For example: ref class Test { public: String^ name; Int32 number; ..... }
11
by: Freddy Coal | last post by:
Hi, I'm trying to read a binary file of 2411 Bytes, I would like load all the file in a String. I make this function for make that: '-------------------------- Public Shared Function...
0
by: Vince Filby | last post by:
Hi, We are working with distributing Lucene.net. We have Master Index Server which takes responsibility of distributing the index searching to multiple Index Servers by calling the remote...
1
by: sandeepbhutani304 | last post by:
have 2 projects communicating each other with .NET remoting. But when I am trying to call these functions I am getting the error: The input stream is not a valid binary format. The starting...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
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: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
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...

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.