473,773 Members | 2,334 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

creating int from contiguous bits in an int

I'd like to be able to create an integer from a range of contiguous
bits
in another integer. I'm on a big-ending machine, in case that matters.
I would ideally like to create a function with this prototype:

unsigned long long extractValue(un signed long long target, int a, int
b)

where a and b are the range of bits counted off from the most
significant
bit (where the msb is the 0th bit). For instance, 12345678900 is

00000000 00000000 00000000 00000010 11011111 11011100 00011100
00110100

A call to extractValue(va lue, 32, 35) should result in 13 (1101 in
binary).

Can someone please help?

Nov 26 '05 #1
7 2283
Digital Puer wrote:
I'd like to be able to create an integer from a range of contiguous
bits
in another integer. I'm on a big-ending machine, in case that matters.
I would ideally like to create a function with this prototype:

unsigned long long extractValue(un signed long long target, int a, int
b)

where a and b are the range of bits counted off from the most
significant
bit (where the msb is the 0th bit). For instance, 12345678900 is

00000000 00000000 00000000 00000010 11011111 11011100 00011100
00110100

A call to extractValue(va lue, 32, 35) should result in 13 (1101 in
binary).

Can someone please help?

You've chosen an unhelpful way of specifying the bits you want. :-)

The idea is that we shift enough bits to the left for the desired MSB to
be the actual MSB, then shift back to make the desired LSB the actual
LSB, losing undesired bits in the overflow. This can be done in one
expression, but I'll do it in more for clarity.

#include <limits.h>

unsigned long long extractValue(un signed long long target, int msb,
int lsb) {
const size_t ull_bits = CHAR_BIT * sizeof(unsigned long long);
unsigned long long result;
if (msb > lsb) {
/* empty range */
result = 0;
} else {
/* shift the desired msb to the actual msb */
result = target << msb;
/* there are (lsb - msb + 1) bits in the range, shift them
from high to low */
result >>= ull_bits - (lsb - msb + 1);
}
return result;
}

This function does not check if the arguments are in range; it assumes
you know what bits you can access.

S.
Nov 26 '05 #2
Digital Puer wrote:
I'd like to be able to create an integer from a range of contiguous
bits
in another integer. I'm on a big-ending machine, in case that matters.
I would ideally like to create a function with this prototype:

unsigned long long extractValue(un signed long long target, int a, int
b)

where a and b are the range of bits counted off from the most
significant
bit (where the msb is the 0th bit). For instance, 12345678900 is

00000000 00000000 00000000 00000010 11011111 11011100 00011100
00110100

A call to extractValue(va lue, 32, 35) should result in 13 (1101 in
binary).

Can someone please help?

I'll try.
First though, why declare msb the 0th bit? It seems arbitrary and
counterintuitiv e in C where we think of the lsb as the 0th. Endianess
does not seem to be an issue.

Using 32 and 35 calculate that you need a four-bit mask and create it.

00000000 00000000 00000000 00000000 00000000 00000000 00000000 00001111

Now shift 'value' right such that the four bits of interest are the
least significant. Now 'and' the shifted value with the mask. Voila, 13.

--
Joe Wright
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Nov 26 '05 #3

Skarmander wrote:
You've chosen an unhelpful way of specifying the bits you want. :-)
What's a better way of specifying the bits?
unsigned long long extractValue(un signed long long target, int msb,
int lsb) {

thank you. This works perfectly.

Nov 26 '05 #4

Joe Wright wrote:
I'll try.
First though, why declare msb the 0th bit? It seems arbitrary and
counterintuitiv e in C where we think of the lsb as the 0th.
Sorry. I guess I'm thinking of the bit representation as a
character array, so '0010' would have the '1' bit in the
array[2] position. That's probably not too helpful.

Using 32 and 35 calculate that you need a four-bit mask and create it.

00000000 00000000 00000000 00000000 00000000 00000000 00000000 00001111

Now shift 'value' right such that the four bits of interest are the
least significant. Now 'and' the shifted value with the mask. Voila, 13.

Thank you for the insight. Here's an implemention based on
your suggestion.
unsigned long long extract(unsigne d long long target, int msb, int lsb)
{
int mask_size = lsb - msb + 1;
unsigned long long mask;
unsigned long long result;
int ull_size = CHAR_BIT * sizeof(unsigned long long);

mask = (1 << mask_size) - 1;
target >>= (ull_size - lsb - 1);
result = mask & target;

return result;

}

Nov 26 '05 #5
Digital Puer wrote:
Skarmander wrote:
You've chosen an unhelpful way of specifying the bits you want. :-)

What's a better way of specifying the bits?

Well, bits are usually numbered from the LSB, starting at 0. Also, a
range specified by its ends needs checking to handle the case when it's
empty. An easier function to write would be

unsigned long long extractBits(uns igned long long source, int low,
int count) {
return (source >> low) && ((1ull << count) - 1);
}

Shorter, clearer, and it doesn't actually need to know how many bits are
in an unsigned long long. But, of course, this may not be what you need
at all, and may instead make things more difficult at the calling end. I
was just making the observation that *if* I had been free to write the
function as conveniently as possible, this would be its interface. :-)

S.
Nov 27 '05 #6
Digital Puer wrote:
Skarmander wrote:
You've chosen an unhelpful way of specifying the bits you want. :-)


What's a better way of specifying the bits?


Specify them as you do with decimal digits
42 base 10
means
4 * 10^1 + 2 * 10^0

Just in the same way,
10 base 2
means
1 * 2^1 + 0 * 2^0

You can leave out leading digits evaluating to zero.
So, if talking about bit 0 (the binary digit associated
with 2^0), everyone knows that it is the least
significant bit and toggles +0/+1 -- irrespective of the
absolute number of available bits.
So, you'd rather go at it like that:
binary ... x ... 1 0 1 1
bit no ... n ... 3 2 1 0

Cheers
Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.
Nov 27 '05 #7

Digital Puer wrote:
I'd like to be able to create an integer from a range of contiguous
bits
in another integer. I'm on a big-ending machine, in case that matters.
I would ideally like to create a function with this prototype:

unsigned long long extractValue(un signed long long target, int a, int
b)

where a and b are the range of bits counted off from the most
significant
bit (where the msb is the 0th bit). For instance, 12345678900 is

00000000 00000000 00000000 00000010 11011111 11011100 00011100
00110100

A call to extractValue(va lue, 32, 35) should result in 13 (1101 in
binary).

Can someone please help?


It's easier going from the lsb rather than the msb, because it makes
the shifting easier. Then you have:

unsigned long long
extractValue(un signed long long target, int a, int b)
{
return (target >> a) & ~(~0ULL << (b - a + 1));
}

Rewriting this to work going from the msb is left as an exercise to the
reader.

Gregory Pietsch

Nov 28 '05 #8

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

Similar topics

19
8829
by: cppaddict | last post by:
Hi, I am going to have a series of bit flags which I could store in an array, or as a string ("10011001"), or any other way. I want to be able to turn this series of bits into an int. I know C++ must have some class or built-in functionality for this, but my web searching thus far hasn't found it. Can someone let me know what I should use?
9
7064
by: Olumide | last post by:
Thats the question. I know about virtual memory, and the MMU. I just wonder if array members guaranteed to be contiguous in physical memory (and if so, why). Thanks, Olumide
3
3374
by: Vish | last post by:
Hi All I have written a program to count the maximum contiguous set bits in an integer . Like if my binary representation of integer is : 1100111 : then output should be 3. 111000111110000101010111111 : then output should be 6. I am including the snippet below. How can I optimize this code and also is there a one liner to
2
1553
by: Amongin Ewinyu | last post by:
Hi, I'm trying to create a Windows service programmatically that will do the following: - When a user logs on, it will automatically run a service that uses BITS (Background Intelligent Transfer Service) to check for the most current version of a file and downloads this version. I have a wrapper class thats imported as a reference in order for me to be
38
5142
by: Peteroid | last post by:
I looked at the addresses in an 'array<>' during debug and noticed that the addresses were contiguous. Is this guaranteed, or just something it does if it can? PS = VS C++.NET 2005 Express using clr:/pure syntax
22
3095
by: divya_rathore_ | last post by:
No pun intended in the subject :) Is dynamically allocated memory contiguous in C++? In C? Deails would be appreciated. warm regards, Divya Rathore (remove underscores for email ID)
22
2636
by: Jack | last post by:
The following code can be compiled. But When I run it, it causes "Segmentation fault". int main(){ char **c1; *c1 = "HOW"; // LINE1 ++(*c1); *c1 = "ARE";
38
3012
by: djhulme | last post by:
Hi, I'm using GCC. Please could you tell me, what is the maximum number of array elements that I can create in C, i.e. char* anArray = (char*) calloc( ??MAX?? , sizeof(char) ) ; I've managed to create arrays using DOUBLE data types, but when I try to access the array, the compiler complains that the number is not an INT, i.e.
9
2063
by: jmcgill | last post by:
Saw this used as an example. Compiles without warnings. "Works." Kosher or not? Why or why not? #include <stdio.h> int main(int argc, char **argv){ int i,j,k,l,m; int *p; i=2; j=4; k=8; l=32; m=64; /*any values*/ p = &i;
0
9454
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10106
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...
0
9914
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
8937
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
7463
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
5484
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4012
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
3610
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2852
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.