473,750 Members | 2,253 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Reading bits from byte (in a file)

Hello.
I need to read bits from bytes in a file.
I have code that works but it's very slow.
Can anybody help me?
The code I have is:

private bool GetBit(byte b, int pos)
{
return ((b & (byte)(1 << pos)) != 0);
}
private int GetBits(byte b, int offset, int count)
{
int number = 0;
for (int i = 1; i <= count; i++)
{
if (GetBit(b, offset + i - 1))
{
switch (i)
{
case 1:
number += 1;
break;
case 2:
number += 2;
break;
case 3:
number += 4;
break;
case 4:
number += 8;
break;
case 5:
number += 16;
break;
case 6:
number += 32;
break;
case 7:
number += 64;
break;
case 8:
number += 128;
break;
}
}
}
return number;
}

Thank you in advance!
Oyvind Eriksen
Jun 25 '06 #1
5 32300
On 2006-06-25, Oyvind Eriksen <oyvind> wrote:
private bool GetBit(byte b, int pos)
{
return ((b & (byte)(1 << pos)) != 0);
}
private int GetBits(byte b, int offset, int count)
{
int number = 0;
for (int i = 1; i <= count; i++)
{
if (GetBit(b, offset + i - 1))
{
switch (i)
{
case 1:
number += 1;
break;
case 2:
number += 2;
break;
case 3:
number += 4;
break;
case 4:
number += 8;
break;
case 5:
number += 16;
break;
case 6:
number += 32;
break;
case 7:
number += 64;
break;
case 8:
number += 128;
break;
}
}
}
return number;
}


How about:

private static int GetBits2(byte b, int offset, int count)
{
int result = 0;
int pow = 1;

b >>= offset;
for (int i = 0; i < count; ++i)
{
if (((byte)1 & b) == 1)
{
result += pow;
}

b >>= 1;
pow *= 2;
}

return result;
}
--
Met vriendelijke groeten,
Tim Van Wassenhove <http://timvw.madoka.be >
Jun 25 '06 #2
"Oyvind Eriksen" <oyvind -(at)- eriksen.cn> wrote:
I need to read bits from bytes in a file.
I have code that works but it's very slow.
Can anybody help me?


You appear to be trying to get the value of a bitfield in a byte. Try
this code:

---8<---
static int GetBits3(byte b, int offset, int count)
{
return (b >> offset) & ((1 << count) - 1);
}
--->8---

My tests show it's about 8 times faster.

-- Barry

--
http://barrkel.blogspot.com/
Jun 25 '06 #3
Thank you so much!
Can you explain how that code works? Or send me to a website that explains
that?
I'm somewhat new to C# and haven't figured out the consept you used and I'm
eager to learn.

Again, thank you!
Oyvind Eriksen

"Barry Kelly" <ba***********@ gmail.com> wrote in message
news:f5******** *************** *********@4ax.c om...
"Oyvind Eriksen" <oyvind -(at)- eriksen.cn> wrote:
I need to read bits from bytes in a file.
I have code that works but it's very slow.
Can anybody help me?


You appear to be trying to get the value of a bitfield in a byte. Try
this code:

---8<---
static int GetBits3(byte b, int offset, int count)
{
return (b >> offset) & ((1 << count) - 1);
}
--->8---

My tests show it's about 8 times faster.

-- Barry

--
http://barrkel.blogspot.com/

Jun 25 '06 #4
"Oyvind Eriksen" <oyvind -(at)- eriksen.cn> wrote:
Thank you so much!
Can you explain how that code works? Or send me to a website that explains
that?
I'm somewhat new to C# and haven't figured out the consept you used and I'm
eager to learn.

---8<---
static int GetBits3(byte b, int offset, int count)
{
return (b >> offset) & ((1 << count) - 1);
}
--->8---


You've got a set of bits in memory that look like this:

00000000

The offset is zero-based, and starts counting from the right.
The count is the number of bits to get. For a (offset, count) of (2,4),
you'd be trying to get these bits:

GGxxxxGG

(I'm using 'xxxx' to represent the bits you're trying to get at, and G
to indicate Garbage that we don't want in the result.)

The three operations used in the code above are >> (shift right), <<
(shift left) and & ("AND" or "mask").

The first step is to move the interesting bits to the right until they
start at offset zero. So, we shift the bits to the right with shift
right (>>) offset times:

GGxxxxGG >> offset => 00GGxxxx

So now we have all our interesting bits positioned from 0..count-1
(counting bits from the right-most place). (0 got shifted in from the
left, because byte is an unsigned number.)

The next thing to do is to remove any uninteresting bits that extend to
the left of our bitfield. For example, the original byte might look like
this:

01001011

after shifting by 2, it would look like:

00010010
____^^^^___ interesting bits

You can see here that any bits left over, to the left of our interesting
bits, would corrupt our result. So, we need to mask them out with the &
operator (the "and" operator).

The value we'd like to use to mask these bits out is "count '1's". For a
count of 4, we need 1111; for a count of 6, we'd need 111111. So, for
our count of 4, we'd like to perform this mask operation:

00GGxxxx
00001111 &
--------
0000xxxx

This removes the garbage because any number and'd with '0' produces 0.

So, the only question is how to turn 'count' into our mask. The way this
is done is simple: every power of two is one more than the sum of the
previous positive powers of two.

For example consider 8, which is 2^3:

2^0 + 2^1 + 2^2 + 1
= 1 + 2 + 4 + 1 = 8

Look at it another way, in binary. Every power of 2 in binary consists
of exactly one digit:

2^0 = 1 = 1
2^1 = 2 = 10
2^2 = 4 = 100
2^3 = 8 = 1000
2^4 = 16 = 10000

What happens when you subtract 1 from these powers of two? You end up
with all the 0's to the right of the 1 becoming 1:

2^0 - 1 = 0 = 0
2^1 - 1 = 1 = 1
2^2 - 1 = 3 = 11
2^3 - 1 = 7 = 111
2^4 - 1 = 15 = 1111

So, here's where the << operator comes in. Shift 1 left by count times,
and you get 2^count. For example, 2^3 = 1 << 3:

1 << 3 = 1000 = 8

So, hopefully you can see where it all comes together. 1 << count is
2^count, and when you subtract 1, that makes all the lesser bits 1 -
which is exactly what we want out of the mask. Getting back to our byte:

00GGxxxx

Our count is 4, so we take 1 << 4:

00010000

And we subtract one:

00001111

This is the mask that's used with earlier, shifted number:

00GGxxxx
00001111 &
--------
xxxx

This mask works because any digit AND'd with 1 remains unchanged.

OK. No more homework for me unless I go back to college :)

-- Barry

--
http://barrkel.blogspot.com/
Jun 25 '06 #5
Hello again.
I never got around to thank you for taking time to explain to me.
If you're not already a teacher, you should be.. :-)
I've never found an easy explaination like you wrote.
Now my program is up an running, at least the "alpha" version.

Again thank you!
I hope I can return the favor some day.

Regards,
Oyvind Eriksen
"Barry Kelly" <ba***********@ gmail.com> wrote in message
news:38******** *************** *********@4ax.c om...
"Oyvind Eriksen" <oyvind -(at)- eriksen.cn> wrote:
Thank you so much!
Can you explain how that code works? Or send me to a website that
explains
that?
I'm somewhat new to C# and haven't figured out the consept you used and
I'm
eager to learn.

> ---8<---
> static int GetBits3(byte b, int offset, int count)
> {
> return (b >> offset) & ((1 << count) - 1);
> }
> --->8---


You've got a set of bits in memory that look like this:

00000000

The offset is zero-based, and starts counting from the right.
The count is the number of bits to get. For a (offset, count) of (2,4),
you'd be trying to get these bits:

GGxxxxGG

(I'm using 'xxxx' to represent the bits you're trying to get at, and G
to indicate Garbage that we don't want in the result.)

The three operations used in the code above are >> (shift right), <<
(shift left) and & ("AND" or "mask").

The first step is to move the interesting bits to the right until they
start at offset zero. So, we shift the bits to the right with shift
right (>>) offset times:

GGxxxxGG >> offset => 00GGxxxx

So now we have all our interesting bits positioned from 0..count-1
(counting bits from the right-most place). (0 got shifted in from the
left, because byte is an unsigned number.)

The next thing to do is to remove any uninteresting bits that extend to
the left of our bitfield. For example, the original byte might look like
this:

01001011

after shifting by 2, it would look like:

00010010
____^^^^___ interesting bits

You can see here that any bits left over, to the left of our interesting
bits, would corrupt our result. So, we need to mask them out with the &
operator (the "and" operator).

The value we'd like to use to mask these bits out is "count '1's". For a
count of 4, we need 1111; for a count of 6, we'd need 111111. So, for
our count of 4, we'd like to perform this mask operation:

00GGxxxx
00001111 &
--------
0000xxxx

This removes the garbage because any number and'd with '0' produces 0.

So, the only question is how to turn 'count' into our mask. The way this
is done is simple: every power of two is one more than the sum of the
previous positive powers of two.

For example consider 8, which is 2^3:

2^0 + 2^1 + 2^2 + 1
= 1 + 2 + 4 + 1 = 8

Look at it another way, in binary. Every power of 2 in binary consists
of exactly one digit:

2^0 = 1 = 1
2^1 = 2 = 10
2^2 = 4 = 100
2^3 = 8 = 1000
2^4 = 16 = 10000

What happens when you subtract 1 from these powers of two? You end up
with all the 0's to the right of the 1 becoming 1:

2^0 - 1 = 0 = 0
2^1 - 1 = 1 = 1
2^2 - 1 = 3 = 11
2^3 - 1 = 7 = 111
2^4 - 1 = 15 = 1111

So, here's where the << operator comes in. Shift 1 left by count times,
and you get 2^count. For example, 2^3 = 1 << 3:

1 << 3 = 1000 = 8

So, hopefully you can see where it all comes together. 1 << count is
2^count, and when you subtract 1, that makes all the lesser bits 1 -
which is exactly what we want out of the mask. Getting back to our byte:

00GGxxxx

Our count is 4, so we take 1 << 4:

00010000

And we subtract one:

00001111

This is the mask that's used with earlier, shifted number:

00GGxxxx
00001111 &
--------
xxxx

This mask works because any digit AND'd with 1 remains unchanged.

OK. No more homework for me unless I go back to college :)

-- Barry

--
http://barrkel.blogspot.com/

Jul 1 '06 #6

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

Similar topics

0
1835
by: Peter A. Schott | last post by:
Got a strange scenario going on here in that I could have sworn this worked yesterday. I am issuing binary retrieval calls to an FTP server, writing to a file, close the file, then removing the file from the remote site. When I do this, I end up with 0 byte files. I was hoping to avoid parsing a list of remote and local files and matching them up that way because it would be easier to remove on successful retrieve. I'm including some...
3
2209
by: SB | last post by:
Hello. I have an input file which is laid out in the following manner... Name Day 1 am time 1 am time 2 appointment pm time 1 pm time 2 appointment Day 2
7
4219
by: laclac01 | last post by:
So I am converting some matlab code to C++. I am stuck at one part of the code. The matlab code uses fread() to read in to a vector a file. It's a binary file. The vector is made up of floats, which in matlab is 32 bits. How do I get this binary file in to floats in c++? I try reading the file using the ifstream>>myFloat. But nothing ever goes in to the float. So the closest I have come is having 4 unsigned char store the binary data....
1
2033
by: Turner, GS \(Geoff\) | last post by:
> -----Original Message----- > From: siliconwafer > Posted At: 19 August 2005 15:20 > Posted To: c > Conversation: reading an excel file in C? > Subject: reading an excel file in C? > > > Hi All, > I want to know,How can one read an Excel file into C,cell by cell?
6
15478
by: Gerald Maher | last post by:
Hi Reading in XML file using C#, changing elements and saving back to the file, how can i do that ? I want to be able to read an XML file and read out Elements. for example <name>Tom</tom> When I read from a file i want to save the XML document in memory of the computer and when i am finished flush it back to the file, that
8
3514
by: Andrew Robert | last post by:
Hi Everyone. I tried the following to get input into optionparser from either a file or command line. The code below detects the passed file argument and prints the file contents but the individual swithces do not get passed to option parser.
4
3473
by: Fazana | last post by:
I need help for reading a text file into in my java program. The file contains this information: ID# Student’s Answers --------------------------- 236499 TFTFTFTFFFFTFTFFFTF 643828 TFTFTTTTTF FTFTFTTF 917057 FTF FTTTFFFTF FTFTFT 656565 FTF FTFTFTF TTFT TTT
6
4035
by: Stephen | last post by:
I am reading a text file using TextReader reader = new StreamReader("file.txt"); like I have done many a times before. I then execute the statement string a = reader.ReadToEnd(); this string is then sent into a function to convert its contents (hex string) into a byte array. Well when this pass occurs the HextoByteArray function says the input is in an invalid format. I think for somereason there is some whitespace/null character at the...
13
3712
by: swetha | last post by:
HI Every1, I have a problem in reading a binary file. Actually i want a C program which reads in the data from a file which is in binary format and i want to update values in it. The file consists of structures of type---- struct record { int acountnum; char name; float value;
2
2842
by: Derik | last post by:
I've got a XML file I read using a file_get_contents and turn into a simpleXML node every time index.php loads. I suspect this is causing a noticeable lag in my page-execution time. (Or the wireless where I'm working could just be ungodly slow-- which it is.) Is reading a file much more resource/processor intensive than, say, including a .php file? What about the act of creating a simpleXML object? What about the act of checking the...
0
8999
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, 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...
0
9575
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
9256
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
8260
agi2029
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...
0
6080
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
4885
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3322
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
2
2798
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2223
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.