474,042 Members | 1,809 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Bit Manipulation

Hi there,

Would the following functions work for bit manipulation? I want to specify
a byte and the bit of the byte (from the MSB down to LSB) and either set it,
clear it or get what it is currently at.
Thanks
Allan

void BitSet(unsigned char *Byte, int Bit)
{
unsigned char Mask = 0x80; // all zeros with a 1 at the MSB

if (Bit>7 || Byte==NULL)
return;

Mask = Mask >> Bit;
*Byte = *Byte | Mask;
}

void BitClr(unsigned char *Byte, int Bit)
{
unsigned char Mask = 0x80; // all zeros with a 1 at the MSB

if (Bit>7 || Byte==NULL)
return;

Mask = ~(Mask >> Bit);
*Byte = *Byte & Mask;
}

int BitGet(unsigned char *Byte, int Bit)
{
unsigned char Mask = 0x80; // all zeros with a 1 at the MSB

if (Bit>7 || Byte==NULL)
return;

Mask = Mask >> Bit;
if ((*Byte & Mask) == Mask)
return 1;
else
return 0;
}

--
Allan Bruce
Dept. of Computing Science
University of Aberdeen
Aberdeen AB24 3UE
Scotland, UK
Nov 13 '05 #1
4 9170
"Allan Bruce" <al*****@TAKEAW AYf2s.com> wrote in message
news:bm******** **@news.freedom 2surf.net...
| Would the following functions work for bit manipulation?
....
| void BitSet(unsigned char *Byte, int Bit)
| {
| unsigned char Mask = 0x80; // all zeros with a 1 at the MSB
Ok if you want to number 0 as the most significant bit,
and 7 as the least significant. This is not the usual
convention I have seen in C: people usually think
in terms of ( 1<<bitPos ).

| if (Bit>7 || Byte==NULL)
| return;
|
| Mask = Mask >> Bit;
| *Byte = *Byte | Mask;

Ok. Note that you could write:
*Byte |= Mask; // but it's a matter of taste...
| }
|
| void BitClr(unsigned char *Byte, int Bit)
| {
| unsigned char Mask = 0x80; // all zeros with a 1 at the MSB
|
| if (Bit>7 || Byte==NULL)
| return;
|
| Mask = ~(Mask >> Bit);
| *Byte = *Byte & Mask;
| }
|
| int BitGet(unsigned char *Byte, int Bit)
| {
| unsigned char Mask = 0x80; // all zeros with a 1 at the MSB
|
| if (Bit>7 || Byte==NULL)
| return;
Error: you need to specify a return value here...

| Mask = Mask >> Bit;
| if ((*Byte & Mask) == Mask)
| return 1;
| else
| return 0;
Ok. But note that the last 4 lines are equivalent to:
return ( (*Byte & Mask)==Mask );
Or:
return ( *Byte & Mask ) ? 1 : 0;
| }
But all in all, your code is mostly ok.

Regards,
Ivan
--
http://ivan.vecerina.com
Nov 13 '05 #2

"Ivan Vecerina" <NONE_use_form@ website_to_cont act_me> wrote in message
news:3f******** @news.swissonli ne.ch...
"Allan Bruce" <al*****@TAKEAW AYf2s.com> wrote in message
news:bm******** **@news.freedom 2surf.net...
| Would the following functions work for bit manipulation?
...
| void BitSet(unsigned char *Byte, int Bit)
| {
| unsigned char Mask = 0x80; // all zeros with a 1 at the MSB
Ok if you want to number 0 as the most significant bit,
and 7 as the least significant. This is not the usual
convention I have seen in C: people usually think
in terms of ( 1<<bitPos ).

| if (Bit>7 || Byte==NULL)
| return;
|
| Mask = Mask >> Bit;
| *Byte = *Byte | Mask;

Ok. Note that you could write:
*Byte |= Mask; // but it's a matter of taste...
| }
|
| void BitClr(unsigned char *Byte, int Bit)
| {
| unsigned char Mask = 0x80; // all zeros with a 1 at the MSB
|
| if (Bit>7 || Byte==NULL)
| return;
|
| Mask = ~(Mask >> Bit);
| *Byte = *Byte & Mask;
| }
|
| int BitGet(unsigned char *Byte, int Bit)
| {
| unsigned char Mask = 0x80; // all zeros with a 1 at the MSB
|
| if (Bit>7 || Byte==NULL)
| return;
Error: you need to specify a return value here...

| Mask = Mask >> Bit;
| if ((*Byte & Mask) == Mask)
| return 1;
| else
| return 0;
Ok. But note that the last 4 lines are equivalent to:
return ( (*Byte & Mask)==Mask );
Or:
return ( *Byte & Mask ) ? 1 : 0;
| }
But all in all, your code is mostly ok.

Regards,
Ivan


Thanks.

I am making a basic huffman coding program, which reads in all the bytes of
a file, sorts them by the frequency they appear in the file, then pairs the
lowest frequencies to produce a kind of tree.
When I pair them up, I am creating a binary code which adds a 1 at the
beginning if the node was the highest of the pair, otherwise it adds a 0 at
the beginning. It is this part that I have reversed so the code bits are
added at the end of the bit patters, but this will be reversed when
outputting to file.
Has anybody coded a basic huffman compression scheme? It would be
interesting to see how they write the info to file, since I have variable
length bit patterns (potentially 2 -> 255 bits). What I am doing is reading
each bit then adding it to the following function:

void Bytify(int xiBit) // takes bits in and once a full byte is recieved,
writes to file
{
static unsigned char lPosition = 0x80;
static unsigned char lByte = 0x0;

if (xiBit) // if the xi bit is set
lByte = lByte | lPosition; // then add it to the char

lPosition = lPosition >> 1; // next position for next time round

if (lPosition == 0x0) // if we are on the last position
{
fputc((int)lByt e, fptr); // write byte to file
lPosition = 0x80; // and reset the postion and the new byte
lByte = 0x0;
}
}
One last thing, if I have the length of the bit field, I am using this to
find out the byte containing the bit, and the bit within that byte:

lBitPosition = loop%8;
lCharPosition = (loop - lBitPosition) / 8;

Where loop is going from 0 to BitPatternLengt h-1. Is this ok? Or is there a
better way to do it?
Thanks
Allan
Nov 13 '05 #3
Allan Bruce wrote:

Hi there,

Would the following functions work for bit manipulation?
I want to specify a byte and the bit of the byte
(from the MSB down to LSB) and either set it,
clear it or get what it is currently at. void BitSet(unsigned char *Byte, int Bit)
{
unsigned char Mask = 0x80; // all zeros with a 1 at the MSB

if (Bit>7 || Byte==NULL)
return;

Mask = Mask >> Bit;
*Byte = *Byte | Mask;
}


It's OK, except that it's eight_bit_centr ic.

#include <stdio.h>
#include <limits.h>

void BitSet(unsigned char *Byte, int Bit)
{
if (Bit > CHAR_BIT - 1 || Byte == NULL) {
return;
}
*Byte |= (((unsigned char)-1 >> 1) + 1) >> Bit;
}

--
pete
Nov 13 '05 #4
"Allan Bruce" <al*****@TAKEAW AYf2s.com> wrote in message
news:bm******** **@news.freedom 2surf.net...
| Has anybody coded a basic huffman compression scheme? It would be
| interesting to see how they write the info to file, since I have variable
| length bit patterns (potentially 2 -> 255 bits).
Well, it's been a long long time for me.
The approach I would take is more or less:

static unsigned char cur=0;
static int freeBits = 8; // # of available bits in *dst

void bitsWriter(unsi gned long newbits, int bitCount)
{
while(bitCount> 0) {
unsigned nbits = bitCount;
if( nbits>freeBits ) nbits = freeBits;
freeBits -= nbits;
bitCount -= nbits;
cur = (cur<<nbits)|(n ewbits>>bitCoun t);
if( freeBits==0 ) { // byte is complete
fputc((int)cur, fptr);
freeBits = 8;
}
}
}
//NB: a flush function needs to be added

Data bits are passed in 'newbits', first bit in MSB,
and last bit aligned on bit zero.
If a huffman code takes more than 32 bits, it will
need to be written using multiple calls.

The buffer 'cur' could be of type unsigned long (e.g. 32 bits)
if you are careful with endianess issues.

| What I am doing is reading
| each bit then adding it to the following function:
|
| void Bytify(int xiBit) // takes bits in and once a full byte is
recieved,
| writes to file
| {
| static unsigned char lPosition = 0x80;
| static unsigned char lByte = 0x0;
|
| if (xiBit) // if the xi bit is set
| lByte = lByte | lPosition; // then add it to the char
|
| lPosition = lPosition >> 1; // next position for next time round
|
| if (lPosition == 0x0) // if we are on the last position
| {
| fputc((int)lByt e, fptr); // write byte to file
| lPosition = 0x80; // and reset the postion and the new byte
| lByte = 0x0;
| }
| }
Seems correct.
Might be slower as the function is called for each bit.

| One last thing, if I have the length of the bit field, I am using this to
| find out the byte containing the bit, and the bit within that byte:
|
| lBitPosition = loop%8;
| lCharPosition = (loop - lBitPosition) / 8;
Ok if 'loop' is positive, but the ' - lBitPosition ' part is unnecessary.
In C, integer divide will automatically round down the value.
So: lCharPosition = loop/8;

| Where loop is going from 0 to BitPatternLengt h-1.
| Is this ok? Or is there a better way to do it?
I would store and transmit the Huffman code word by word,
for efficiency reasons:

void sendCode( //NB: assuming 32-bit longs
int bitLen,
unsigned long codeBuf[32]) // 8*32 = 256 bits
{
while(bitLen>32 ) {
bitsWriter( codeBuf, 32);
++codeBuf;
bitLen-=32;
}
bitsWriter( codeBuf, bitLen ); // last (incomplete) word
}

But your code was correct. It is better to first write your encoder
in a way that you can easily understand, and then to look into
performance improvements...
Regards,
Ivan
--
http://ivan.vecerina.com
Nov 13 '05 #5

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

Similar topics

2
6103
by: Marcus | last post by:
I am having some problems with trying to perform calculations on time fields. Say I have a start time and an end time, 1:00:00 and 2:30:00 (on a 24 hour scale, not 12). I want to find the difference in minutes, divide this result by a predefined size of interval, and make a loop that runs this many times. For example, with an interval size of 15 minutes, it will return 6 blocks... I have this all working fine, but am getting stuck on...
4
5454
by: Rune Johansen | last post by:
Hi. I'm doing some image manipulation in an applet using the example code on this page: http://www.akop.org/art/pixels3.htm However, I really want an application rather than an applet, I just can't figure out how to do the image loading and manipulation when it's not from inside an applet. Any hints on the subject are appreciated.
3
1885
by: Sam | last post by:
Hello, in my coding work I'm going to using a lot of matix manipulation, just basic matrix addition, multiplication, Gaussian method solving for roots, least square... But I don't know if there's a library which defines matrix and its manipulation. I know there must be one and it's somethere but I just have no experience. Thanks.
9
2608
by: I. Kobrinsky | last post by:
I'm new here. I started a personal password-program, a trial that includes username, logincounter and password. So my intention is to hide pwd while tipping. So I'm thinking about two popular ways to realize, like using cursor manipulation to backup & delete letters or otherwise to use getch to read them quetly. Maybe somebody here knows and will tell me about potentially dis-/advantages of each method. Meaning especially *intern*
9
2161
by: Job | last post by:
Hi, I would like to find out what ASP/ASP.net can do with image manipulation. Does ASP have built in functions (eg. after upload to server) to manipulate images, like rotate, scale, crop etc.? Or are 3rd party solutions needed to do this? I am a php/codfusion programmer and know nothing about asp, so I'm hoping somebody here can help me out.
4
3513
by: WaterWalk | last post by:
Hello, I'm currently learning string manipulation. I'm curious about what is the favored way for string manipulation in C, expecially when strings contain non-ASCII characters. For example, if substrings need be replaced, or one character needs be changed, what shall I do? Is it better to convert strings to UCS-32 before manipulation? But on Windows, wchar_t is 16 bits which isn't enough for characters which can't be simply encoded...
8
2031
by: shotokan99 | last post by:
i have this situation. i have a query string: http://www.myquerystring.com?x=xxxxx what this url does is it will return or start downloading a .png file. what i wanted to do is trap this png file and manipuate the image like resizing, color...etc. how can i do this?
0
2605
by: L'eau Prosper Research | last post by:
Press Release: L'eau Prosper Research (Website: http://www.leauprosper.com) releases new TradeStation 8 Add-on - L'eau Prosper Market Manipulation Profiling Tools Set. L'eau Prosper Market Manipulation Profiling Tools Set is a set of advanced tools that help Serious Traders analyze the market direction, market manipulative behavior and predicting the change of trend.
0
2367
by: L'eau Prosper Research | last post by:
NEW TradeStation 8 Add-on - L'eau Prosper Market Manipulation Profiling Tools Set By L'eau Prosper Research Press Release: L'eau Prosper Research (Website: http://www.leauprosper.com) releases new TradeStation 8 Add-on - L'eau Prosper Market Manipulation Profiling Tools Set. L'eau Prosper Market Manipulation Profiling Tools Set is a set of
0
12135
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...
1
12012
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
11138
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
10306
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...
1
8693
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7865
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
6650
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...
1
5408
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
3
3967
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.