Solved

# Set bits

Posted on 2006-07-01
306 Views
I would like to set each bit in a byte, then write the byte out to a binary file.
I then need to take a value from 0 - 12, convert it to 4 bits, then write the 4 bits out to a file.

Could someone provide me with some sample code?

This is running on a linux platform.  Thanks!
0
Question by:jewee
• 2
• 2
• 2

LVL 16

Accepted Solution

PaulCaswell earned 400 total points
ID: 17025156
Hi jewee,

The clearest way to set all bits in a byte is to set it to -1 (with casts if necessary).

I am sure you can do a loop from 0 to 12.

Writing 4 bits to a file is impossible, file writing is restricted to a minimum of 8-bit bytes. Are you expected to write these bytes out as '1'/'0' characters?

Paul
0

Author Comment

ID: 17025162
For the 4 bit value - there is also an additional 4 bit value following this.

I don't need a loop from 0 - 12.  I need to have a function which will take in a value ranging from 0 - 12, and convert it to 4 bits.
0

LVL 16

Expert Comment

ID: 17025263
jewee,

A number taking 4 bits can range between 0 and 15. You already have only 4 bits! Why is this difficult?

Have a go at some code and post it describing your difficulties.

Paul
0

Expert Comment

ID: 17025382
Paul's right; the number from 0-12 will already be using no more than four bits. If you want to convert it to ASCII, just do a loop from 0 to 3 and perform an "AND" against the number with one bit set depending on the value of the counter in the loop.
0

Assisted Solution

dark_archon earned 100 total points
ID: 17025401
And to output the two four-bit values to the file, do something like the following:

fputc( ( a << 4 ) | ( b & 0x0F ), fpout );

The left shift by four bits moves the value, a, into the higher "nibble", eliminating the four bits that were previously there. The b & 0x0F clears the higher four bits, leaving the lower four bits in place. And "OR" operation merges them together into the one byte.
0

Author Comment

ID: 17025514
Paul,

Sorry, I originally misunderstood your question.  thank you.
0

## Featured Post

### Suggested Solutions

Have you thought about creating an iPhone application (app), but didn't even know where to get started? Here's how: ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ Important pre-programming comments: I’ve never tri…
This tutorial is posted by Aaron Wojnowski, administrator at SDKExpert.net.  To view more iPhone tutorials, visit www.sdkexpert.net. This is a very simple tutorial on finding the user's current location easily. In this tutorial, you will learn ho…
The goal of this video is to provide viewers with basic examples to understand opening and writing to files in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use conditional statements in the C programming language.