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

Home Posts Topics Members FAQ

bits of this, bits of that

Ben
Hi,

I need to write some data types into an array of unsigned chars.

These are basically "signals" within a message, so each signal will have
a start bit and a length. The signals will also have a type, one of:
unsigned long
signed long
float
double

The signals with float and double will be 32 or 64 bits long, as
appropriate.

I need to just shift the bits and throw them into the array, untouched.
Whats the best way of doing this?

Since I can't bit shift a float around, I was thinking of a union of the
4 types, and doing all the bit twiddling using the unsigned type. Is
this going to work, or am I asking for trouble? Presumably there's a
better way.

Cheers for any insights,

Ben
--
I'm not just a number. To many, I'm known as a String...
Aug 25 '05 #1
14 2458
> Hi,

I need to write some data types into an array of unsigned chars.

These are basically "signals" within a message, so each signal will have
a start bit and a length. The signals will also have a type, one of:
unsigned long
signed long
float
double

The signals with float and double will be 32 or 64 bits long, as
appropriate.

I need to just shift the bits and throw them into the array, untouched.
Whats the best way of doing this?

Since I can't bit shift a float around, I was thinking of a union of the
4 types, and doing all the bit twiddling using the unsigned type. Is
this going to work, or am I asking for trouble? Presumably there's a
better way.

Cheers for any insights,

Ben
--
I'm not just a number. To many, I'm known as a String...


I'm not sure I completely understand what you're trying to accomplish.
But looks like std::bitset can help you out here. Its a bit-vector and
provides constant time access to the bits. You can also shift around
bits and use bitwise operators on it.

Srini

Aug 25 '05 #2
Ben
Srini wrote:
Hi,

I need to write some data types into an array of unsigned chars.

These are basically "signals" within a message, so each signal will have
a start bit and a length. The signals will also have a type, one of:
unsigned long
signed long
float
double

The signals with float and double will be 32 or 64 bits long, as
appropriate .

I need to just shift the bits and throw them into the array, untouched.
Whats the best way of doing this?

Since I can't bit shift a float around, I was thinking of a union of the
4 types, and doing all the bit twiddling using the unsigned type. Is
this going to work, or am I asking for trouble? Presumably there's a
better way.

Cheers for any insights,

I'm not sure I completely understand what you're trying to accomplish.


OK, I'm trying to pack signals into a data frame to be sent over a
communications channel. Those signals can have 4 distinct types, which
are known a priori for each frame. The signals have a length (which may
be restricted by it's type), and a start bit within the frame.

So, a Signal of type float, would have 32 bits, and could start at say,
the 5 bit within a 64bit data frame.
But looks like std::bitset can help you out here. Its a bit-vector and
provides constant time access to the bits. You can also shift around
bits and use bitwise operators on it.


Thats interesting, but what is the recommended way of getting the bits
in my float into and out of the bitset?

Ben
--
I'm not just a number. To many, I'm known as a String...
Aug 25 '05 #3
> OK, I'm trying to pack signals into a data frame to be sent over a
communications channel. Those signals can have 4 distinct types, which
are known a priori for each frame. The signals have a length (which may
be restricted by it's type), and a start bit within the frame.

So, a Signal of type float, would have 32 bits, and could start at say,
the 5 bit within a 64bit data frame.

I don't think using floating point types and using them to pack data
into a frame is a good idea. If its just a particular number of bits
you want to use to pack into a frame, you can use std::bitset.

Ex: If you want 50 bits,

std::bitset<50> bits_50;

You can get the unsigned long value of any bitset.

And I still don't understand what you mean by "type of a signal". If
you want to capture the type of a signal in the frame you're sending so
that the other side can know what type of signal is in the frame, then
why not designate 2 bits in the frame to indicate the type of signal.

00 - unsigned long
01 - signed long
10 - float
11 - double

Would this meet your requirement or am I still wrong in understnading
your problem?
But looks like std::bitset can help you out here. Its a bit-vector and
provides constant time access to the bits. You can also shift around
bits and use bitwise operators on it.


Thats interesting, but what is the recommended way of getting the bits
in my float into and out of the bitset?


I do not know of any portable way of doing this. If you want to pack
the bits from a float variable into the frame, you could do a (an ugly)
reinterpret_cas t.
Ben
--
I'm not just a number. To many, I'm known as a String...


Srini

Aug 25 '05 #4

Ben schreef:
Srini wrote:
Hi,

I need to write some data types into an array of unsigned chars.

These are basically "signals" within a message, so each signal will have
a start bit and a length. The signals will also have a type, one of:
unsigned long
signed long
float
double

The signals with float and double will be 32 or 64 bits long, as
appropriate .

I need to just shift the bits and throw them into the array, untouched.
Whats the best way of doing this?

Since I can't bit shift a float around, I was thinking of a union of the
4 types, and doing all the bit twiddling using the unsigned type. Is
this going to work, or am I asking for trouble? Presumably there's a
better way.

Cheers for any insights,

I'm not sure I completely understand what you're trying to accomplish.


OK, I'm trying to pack signals into a data frame to be sent over a
communications channel. Those signals can have 4 distinct types, which
are known a priori for each frame. The signals have a length (which may
be restricted by it's type), and a start bit within the frame.


Do you know the formats of the wire types? Are they identical to the
C++ types? After all, ISO C++ does not prescribe how the bits in a type
are used. In fact, for any type but char, there are at least 2 common
implementations (for char, the common implementation is 8 bits, but
even
this is not universal)
So, a Signal of type float, would have 32 bits, and could start at say,
the 5 bit within a 64bit data frame.


However, your C++ float may be 64 bits. Trouble...
But looks like std::bitset can help you out here. Its a bit-vector and
provides constant time access to the bits. You can also shift around
bits and use bitwise operators on it.


Thats interesting, but what is the recommended way of getting the bits
in my float into and out of the bitset?


The best way would be to find out what your wire protocol is (probably
1 sign bit, M mantissa bits and E exponent bits), calclulate the two
unsigned longs MBits and Ebits, with MBits < (1<<M) and EBits < (1<<E)
then add the sign bit, the lower M bits from MBits and the lower E bits
from EBits. If the base is 2, EBits is simple, calculate the 2-log. You
can then divide by 1<<EBits (or multiply by 1<<-EBits) to get MBits.
(base-16 is only a bit more tricky)

The advantage is that the algortihm works on the value of your float,
not the representation of this value in memory.

HTH,
Michiel Salters

Aug 25 '05 #5
"Ben" <benpope81@_pan ts_gmail.com> wrote in message
news:1124966345 .3ee8ba9c41fbfb 7817a747c0f7c4b 794@teranews...
Hi,

I need to write some data types into an array of unsigned chars.

These are basically "signals" within a message, so each signal will have a
start bit and a length. The signals will also have a type, one of:
unsigned long
signed long
float
double

The signals with float and double will be 32 or 64 bits long, as
appropriate.

I need to just shift the bits and throw them into the array, untouched.
Whats the best way of doing this?

Since I can't bit shift a float around, I was thinking of a union of the 4
types, and doing all the bit twiddling using the unsigned type. Is this
going to work, or am I asking for trouble? Presumably there's a better
way.

Cheers for any insights,


Why do you need different data types for the signals? I'd recommend to take
a look at vector<bool> or at the bitset classes for your application.

Cheers
Chris
Aug 25 '05 #6
Ben
msalters wrote:
Ben schreef:


That confused me for a moment, I wondered Ben schreef was!
OK, I'm trying to pack signals into a data frame to be sent over a
communication s channel. Those signals can have 4 distinct types, which
are known a priori for each frame. The signals have a length (which may
be restricted by it's type), and a start bit within the frame.

Do you know the formats of the wire types? Are they identical to the
C++ types? After all, ISO C++ does not prescribe how the bits in a type
are used. In fact, for any type but char, there are at least 2 common
implementations (for char, the common implementation is 8 bits, but
even
this is not universal)


Yep, that problem I know about. There is only one platform / compiler
and it's correct.
So, a Signal of type float, would have 32 bits, and could start at say,
the 5 bit within a 64bit data frame.

However, your C++ float may be 64 bits. Trouble...


As above.
Thats interesting, but what is the recommended way of getting the bits
in my float into and out of the bitset?

The best way would be to find out what your wire protocol is (probably
1 sign bit, M mantissa bits and E exponent bits), calclulate the two
unsigned longs MBits and Ebits, with MBits < (1<<M) and EBits < (1<<E)
then add the sign bit, the lower M bits from MBits and the lower E bits
from EBits. If the base is 2, EBits is simple, calculate the 2-log. You
can then divide by 1<<EBits (or multiply by 1<<-EBits) to get MBits.
(base-16 is only a bit more tricky)

The advantage is that the algortihm works on the value of your float,
not the representation of this value in memory.


Yeah, understood. I might just have to go this route.

Ben
Aug 25 '05 #7
Ben
Srini wrote:
OK, I'm trying to pack signals into a data frame to be sent over a
communication s channel. Those signals can have 4 distinct types, which
are known a priori for each frame. The signals have a length (which may
be restricted by it's type), and a start bit within the frame.

So, a Signal of type float, would have 32 bits, and could start at say,
the 5 bit within a 64bit data frame.
I don't think using floating point types and using them to pack data
into a frame is a good idea.


I need to pack the floating point number into the frame, whether it's a
good thing to do or not is not up to me, I'm just providing the
functionality for my users. The data is specified as the format my
compiler uses, so I literally just need to transfer the bits in and out.
If its just a particular number of bits
you want to use to pack into a frame, you can use std::bitset.

Ex: If you want 50 bits,

std::bitset<50> bits_50;

You can get the unsigned long value of any bitset.
OK.
And I still don't understand what you mean by "type of a signal". If
you want to capture the type of a signal in the frame you're sending so
that the other side can know what type of signal is in the frame, then
why not designate 2 bits in the frame to indicate the type of signal.

00 - unsigned long
01 - signed long
10 - float
11 - double

Would this meet your requirement or am I still wrong in understnading
your problem?


The signal types are known a priori, so there is no requirement to
specify the type, length etc within the frame. I just need the 32 bits
of a float or 64 bits of a double to be in the frame, offset by the
required startbit.
Thats interesting, but what is the recommended way of getting the bits
in my float into and out of the bitset?


I do not know of any portable way of doing this. If you want to pack
the bits from a float variable into the frame, you could do a (an ugly)
reinterpret_cas t.


Hmm, can't seem to make reinterpret_cas t work:
#include <iostream>
#include <bitset>
#include <string>
#include <sstream>
#include <stdexcept>

class Frame {
public:
static const LENGTH = 64;
typedef std::bitset<LEN GTH> Data;
Frame() : data_(0) {}
void SetSignal(size_ t startBit, size_t length, unsigned long value) {
if (64 < startBit + length) {
throw std::range_erro r("Signal too long");
} else {
Data mask = ~(0xffffffff<<( length));
Data temp(value & mask.to_ulong() );
data_ &= ~(mask<<(LENGTH-startBit-length));
data_ |= temp<<(LENGTH-startBit-length);
}
}
unsigned long GetSignal(size_ t startBit, size_t length) {
if (64 < startBit + length) {
throw std::range_erro r("Signal too long");
} else {
Data mask = ~(0xffffffff<<( length));
Data temp = data_>>(LENGTH-startBit-length);
temp &= mask;
return temp.to_ulong() ;
}
}

std::string ToString() {
std::stringstre am ss;
for (int i = LENGTH-1; i>=0; --i) {
if (7 == i%8) {
ss << std::endl << 7-i/8 << ": ";
} else if (3 == i%4) {
ss << " ";
}
ss << data_[i];
}
return ss.str();
}
private:
Data data_;
};

int main(int argc, char* argv[])
{
Frame frame;

std::cout << frame.ToString( ) << std::endl << std::hex;

int intVal = 0x55;
frame.SetSignal (32, 8, intVal);
std::cout << frame.ToString( ) << std::endl;
std::cout << "0x" << frame.GetSignal (32, 8) << std::endl;

float floatVal = 47/5;
frame.SetSignal (0, 32, reinterpret_cas t<unsigned long>(floatVal) );
std::cout << frame.ToString( ) << std::endl;
std::cout << "0x" << reinterpret_cas t<float>(frame. GetSignal(0, 32))
<< std::endl;

return 0;
}

What do you think? In VC7.1 I get:

test.cpp(61): error C2440: 'reinterpret_ca st' : cannot convert from
'float' to 'unsigned long'
Conversion is a valid standard conversion, which can be
performed implicitly or by use of static_cast, C-style cast or
function-style cast
Ben
--
I'm not just a number. To many, I'm known as a String...
Aug 25 '05 #8
Ben wrote:
[snip]
Thats interesting, but what is the recommended way of getting the bits
in my float into and out of the bitset?
I do not know of any portable way of doing this. If you want to pack
the bits from a float variable into the frame, you could do a (an ugly)
reinterpret_cas t.


Hmm, can't seem to make reinterpret_cas t work:

[snip] float floatVal = 47/5;
frame.SetSignal (0, 32, reinterpret_cas t<unsigned long>(floatVal) );


If you want to use reinterpret_cas t to do a bit-wise copy of a float
into a 32-bit int, you probably want something like this:

assert( sizeof(float) == sizeof(unsigned long) );
unsigned long uintVal = *reinterpret_ca st<unsigned long*>( &floatVal
);

A compile-time assertion would be better than a run-time one, however.
See the Boost or Loki libraries for examples.

Cheers! --M

Aug 25 '05 #9
mlimber wrote:
Ben wrote:
[snip]
Thats interesting, but what is the recommended way of getting the bits
in my float into and out of the bitset?

I do not know of any portable way of doing this. If you want to pack
the bits from a float variable into the frame, you could do a (an ugly)
reinterpret_ cast.


Hmm, can't seem to make reinterpret_cas t work:


[snip]
float floatVal = 47/5;
frame.SetSignal (0, 32, reinterpret_cas t<unsigned long>(floatVal) );

If you want to use reinterpret_cas t to do a bit-wise copy of a float
into a 32-bit int, you probably want something like this:

assert( sizeof(float) == sizeof(unsigned long) );
unsigned long uintVal = *reinterpret_ca st<unsigned long*>( &floatVal
);

A compile-time assertion would be better than a run-time one, however.
See the Boost or Loki libraries for examples.


OK, I get it, cheers.

I seem to have it working with a nasty union at the moment, but the cast makes sense now I see it.

Ben
--
I'm not just a number. To many, I'm known as a String...
Aug 25 '05 #10

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

Similar topics

19
8820
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?
11
2583
by: Steve | last post by:
Hi, i know this is an old question (sorry) but its a different problem, i need to write a binary file as follows 00000011 00000000 00000000 00000101 00000000 11111111
13
2082
by: Tomás | last post by:
The quantity of bits used by an unsigned integer type in memory can be determined by: typedef unsigned long long UIntType; CHAR_BIT * sizeof(UIntType) However, what would be a good portable way to determine how many of these
12
2259
by: Frederick Gotham | last post by:
Over on comp.lang.c, Hallvard B Furuseth devised a compile-time constant representing the amount of value representation bits in an unsigned integer type. In true C fashion, here it is as a macro: /* Number of bits in inttype_MAX, or in any (1<<k)-1 where 0 <= k < 3.2E+ 10 */ #define IMAX_BITS(m) ((m) /((m)%0x3fffffffL+1) /0x3fffffffL %0x3fffffffL *30 \ + (m)%0x3fffffffL /((m)%31+1)/31%31*5 + 4-12/((m)%
14
3651
by: evangeli | last post by:
Hello, How can I know the number of bits used for an int value? Is "sizeof(int) * CHAR_BIT" correct ? thanks
23
439
by: Umesh | last post by:
This is a basic thing. Say A=0100 0001 in ASCII which deals with 256 characters(you know better than me!) But we deal with only four characters and 2 bits are enough to encode them. I want to confirm if we can encode A in 2bits(say 00), B in 2 bits (01), C in 2 bits(10) and D in 2 bits by some program. I only use this four alphabet in my work. Can u pl write a sample program to reach my goal?
11
14664
by: Mack | last post by:
Hi all, I want to write a program to count number of bits set in a number. The condition is we should not loop through each bit to find whether its set or not. Thanks in advance, -Mukesh
77
4275
by: borophyll | last post by:
As I read it, C99 states that a byte is an: "addressable unit of data storage large enough to hold any member of the basic character set of the execution environment" (3.6) and that a byte must be at least 8 bits: "The values given below shall be replaced by constant expressions suitable for use in #if
29
2965
by: Virtual_X | last post by:
As in IEEE754 double consist of sign bit 11 bits for exponent 52 bits for fraction i write this code to print double parts as it explained in ieee754 i want to know if the code contain any bug , i am still c++ beginner
11
1857
by: JoeC | last post by:
I am working on a graphics program but my question has nothing to do with graphics but trying to get an algorithm to work. I set graphics from a 16x16 grid to bits of a graphic with: bitData = binTemp * 128 + binTemp * 64 + binTemp * 32 + binTemp * 16 + binTemp * 8 + binTemp * 4 + binTemp * 2 + binTemp; But I want to populate that same pad from bits:
1
9338
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
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...
1
6803
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
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.