473,770 Members | 4,544 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

bytes to unsigned long

Hi All,
I need to convert 4 bytes to an unsigned long.
Suppose I have one array like unsigned char buf[4].I need to convert
these 4 bytes into a single
unsigned long. Is the following piece of code is right??Or is it a
right approch to do that??

unsigned long temp;
temp= (unsigned long) buff[3];
temp | =((unsigned long) buff[2]) << 8;
temp | =((unsigned long) buff[1]) << 16
temp | =((unsigned long) buff[0]) << 24;

Waiting for your suggestions.

May 9 '07 #1
14 12325
"moumita" <mo**********@t ataelxsi.co.inw rote in message
news:11******** **************@ p77g2000hsh.goo glegroups.com.. .
Hi All,
I need to convert 4 bytes to an unsigned long.
Suppose I have one array like unsigned char buf[4].I need to convert
these 4 bytes into a single
unsigned long. Is the following piece of code is right??Or is it a
right approch to do that??

unsigned long temp;
temp= (unsigned long) buff[3];
temp | =((unsigned long) buff[2]) << 8;
temp | =((unsigned long) buff[1]) << 16
temp | =((unsigned long) buff[0]) << 24;

Waiting for your suggestions.
There are a few ways to do it. One way I've done it in the past is to
simply treat a unsigned long as a char array and load the bytes in. Endian
may be an issue.

unsigned long temp;
for ( int i = 0; i < sizeof( unsigned long ); ++i )
(reinterpret_ca st<char*>(&temp ))[i] = buff[i];

The advantage of this is that it works on any size of unsigned long, just
gotta make sure the buffer is long enough. How the buffer was loaded with
the unsigned long also may matter (big .vs. little endian).

I've seen your method used, however.
May 9 '07 #2
On May 9, 8:44 am, moumita <moumitagh...@t ataelxsi.co.inw rote:
I need to convert 4 bytes to an unsigned long.
Suppose I have one array like unsigned char buf[4].I need to convert
these 4 bytes into a single
unsigned long. Is the following piece of code is right??Or is it a
right approch to do that??
unsigned long temp;
temp= (unsigned long) buff[3];
temp | =((unsigned long) buff[2]) << 8;
temp | =((unsigned long) buff[1]) << 16
temp | =((unsigned long) buff[0]) << 24;
Maybe. It's the right approach, anyway. The question is where
the four bytes come from. If they're from an Internet protocol,
it's correct.

You might prefer using uint32_t instead of unsigned long. It's
not present in the current version of the C++ standard, but it
will be part of the next version, and it is already standard C,
so it should be supported by most compilers (provided you
include <stdint.h>, of course). On many modern machines,
unsigned long is 64 bits. (Not that it really matters here.)

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

May 9 '07 #3
moumita wrote:
Hi All,
I need to convert 4 bytes to an unsigned long.
Suppose I have one array like unsigned char buf[4].I need to convert
these 4 bytes into a single
unsigned long. Is the following piece of code is right??Or is it a
right approch to do that??

unsigned long temp;
temp= (unsigned long) buff[3];
temp | =((unsigned long) buff[2]) << 8;
temp | =((unsigned long) buff[1]) << 16
temp | =((unsigned long) buff[0]) << 24;

Waiting for your suggestions.
You may need to worry about endianness...

I posted one of these things a while back ... oh here it is.
http://groups.google.com/group/comp....1db1be797a255f

I attached an example of how you can do it. It's kind of the whole hog,
it allows you to simply re-interpret cast and read the value in the
correct byte order.


template <class base_type, bool wire_is_big_end ian = true >
class NetworkOrder
{
public:

base_type m_uav;

static inline bool EndianCheck()
{
unsigned x = 1;
return wire_is_big_end ian == ! ( * ( char * )( & x ) );
}

static inline void OrderRead(
const base_type & i_val,
base_type & i_destination
)
{
unsigned char * src = ( unsigned char * ) & i_val;
unsigned char * dst = ( unsigned char * ) & i_destination;

if (
( sizeof( base_type ) == 1 )
|| EndianCheck()
) {

//
// Alignment is an issue some architectures so
// even for non-swapping we read a byte at a time

if ( sizeof( base_type ) == 1 ) {
dst[0] = src[0];
} else if ( sizeof( base_type ) == 2 ) {
dst[0] = src[0];
dst[1] = src[1];
} else if ( sizeof( base_type ) == 4 ) {
dst[0] = src[0];
dst[1] = src[1];
dst[2] = src[2];
dst[3] = src[3];
} else {

for (
int i = sizeof( base_type );
i 0;
i --
) {
* ( dst ++ ) = * ( src ++ );
}
}

} else {

if ( sizeof( base_type ) == 2 ) {
dst[1] = src[0];
dst[0] = src[1];
} else if ( sizeof( base_type ) == 4 ) {
dst[3] = src[0];
dst[2] = src[1];
dst[1] = src[2];
dst[0] = src[3];
} else {
dst += sizeof( base_type ) -1;
for ( int i = sizeof( base_type ); i 0; i -- ) {
* ( dst -- ) = * ( src ++ );
}
}
}
}

static inline void OrderWrite(
const base_type & i_val,
base_type & i_destination
)
{
// for the time being this is the same as OrderRead
OrderRead( i_val, i_destination );
}

inline operator base_type () const
{
base_type l_value;
OrderRead( m_uav, l_value );
return l_value;
}

inline base_type operator=( base_type in_val )
{
OrderWrite( in_val, m_uav );
return in_val;
}

};
#if 1
#include <iostream>

struct wire_data_littl e_endian
{
NetworkOrder<un signed long, false a;
};
struct wire_data_big_e ndian
{
NetworkOrder<un signed long, true a;
};
int main()
{
{
char buff[5] = { 1, 2, 3, 4, 0 };

wire_data_littl e_endian & data = * reinterpret_cas t<wire_data_lit tle_endian *>( buff );

unsigned long x = data.a;

std::cout << "little value " << std::hex << x << "\n";

data.a = 0x41424344UL;

std::cout << "little buff " << buff << "\n";
}

{
char buff[5] = { 1, 2, 3, 4, 0 };

wire_data_big_e ndian & data = * reinterpret_cas t<wire_data_big _endian *>( buff );

unsigned long x = data.a;

std::cout << "big endian value " << std::hex << x << "\n";

data.a = 0x41424344UL;

std::cout << "big endian buff " << buff << "\n";
}

}

#endif

May 9 '07 #4
On May 9, 12:21 pm, "Jim Langston" <tazmas...@rock etmail.comwrote :
"moumita" <moumitagh...@t ataelxsi.co.inw rote in message

news:11******** **************@ p77g2000hsh.goo glegroups.com.. .
Hi All,
I need to convert 4 bytes to an unsigned long.
Suppose I have one array like unsigned char buf[4].I need to convert
these 4 bytes into a single
unsigned long. Is the following piece of code is right??Or is it a
right approch to do that??
unsigned long temp;
temp= (unsigned long) buff[3];
temp | =((unsigned long) buff[2]) << 8;
temp | =((unsigned long) buff[1]) << 16
temp | =((unsigned long) buff[0]) << 24;
Waiting for your suggestions.

There are a few ways to do it. One way I've done it in the past is to
simply treat a unsigned long as a char array and load the bytes in. Endian
may be an issue.

unsigned long temp;
for ( int i = 0; i < sizeof( unsigned long ); ++i )
(reinterpret_ca st<char*>(&temp ))[i] = buff[i];

The advantage of this is that it works on any size of unsigned long, just
gotta make sure the buffer is long enough. How the buffer was loaded with
the unsigned long also may matter (big .vs. little endian).

I've seen your method used, however.
thank u all for the reply

May 9 '07 #5
moumita wrote:
Hi All,
I need to convert 4 bytes to an unsigned long.
Suppose I have one array like unsigned char buf[4].I need to convert
these 4 bytes into a single
unsigned long. Is the following piece of code is right??Or is it a
right approch to do that??

unsigned long temp;
temp= (unsigned long) buff[3];
temp | =((unsigned long) buff[2]) << 8;
temp | =((unsigned long) buff[1]) << 16
temp | =((unsigned long) buff[0]) << 24;

Waiting for your suggestions.
That's one way to do it, assuming that you've figured out your
endianness and that unsigned long is at least 32 bits on your system.
An alternate method is to use a union, as in something like this:

union ulong_u
{
unsigned long ul;
unsigned char uc[4];
};

//...

ulong_u u;
std::memcpy(&u. uc, &buf, 4);
unsigned long temp = u.ul;

Of course, you may have to shuffle the bytes that you assign to u.uc to
handle endianness correctly.

Rennie deGraaf
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.7 (GNU/Linux)

iD8DBQFGQYi1IvU 5mZP08HERAhBjAJ 4mKgI7tfbOKUO2D 6OinkKoLti1VwCg roze
CR3c6XXsc29SR7e YeYIZPJ0=
=nUFL
-----END PGP SIGNATURE-----

May 9 '07 #6
Gianni Mariani wrote:
posting redacted
Please don't post attachments to c.l.c++:
http://www.parashift.com/c++-faq-lit...t.html#faq-5.4
May 9 '07 #7
red floyd wrote:
Gianni Mariani wrote:
posting redacted

Please don't post attachments to c.l.c++:
http://www.parashift.com/c++-faq-lit...t.html#faq-5.4
Rules are meant to be broken....

That one in particular.
May 9 '07 #8
On May 9, 7:21 pm, "Jim Langston" <tazmas...@rock etmail.comwrote :
Hi All,
I need to convert 4 bytes to an unsigned long.

There are a few ways to do it. One way I've done it in the past is to
simply treat a unsigned long as a char array and load the bytes in. Endian
may be an issue.

unsigned long temp;
for ( int i = 0; i < sizeof( unsigned long ); ++i )
(reinterpret_ca st<char*>(&temp ))[i] = buff[i];
This way , and Rennie deGraaf's way, are non-portable. You might
cause a program crash by creating a bit pattern that is not valid for
an unsigned long, and also you don't have any control over what
integer you get out of the bytes you put in.

The only reliable method is the one used in the OP code.
AFAIC any time you have to say "endian might be an issue",
there's something wrong with your algorithm.
May 9 '07 #9
On May 9, 9:21 am, "Jim Langston" <tazmas...@rock etmail.comwrote :
"moumita" <moumitagh...@t ataelxsi.co.inw rote in message
news:11******** **************@ p77g2000hsh.goo glegroups.com.. .
I need to convert 4 bytes to an unsigned long.
Suppose I have one array like unsigned char buf[4].I need to convert
these 4 bytes into a single
unsigned long. Is the following piece of code is right??Or is it a
right approch to do that??
unsigned long temp;
temp= (unsigned long) buff[3];
temp | =((unsigned long) buff[2]) << 8;
temp | =((unsigned long) buff[1]) << 16
temp | =((unsigned long) buff[0]) << 24;
Waiting for your suggestions.
There are a few ways to do it. One way I've done it in the past is to
simply treat a unsigned long as a char array and load the bytes in. Endian
may be an issue.
As may be any number of other issues.
unsigned long temp;
for ( int i = 0; i < sizeof( unsigned long ); ++i )
(reinterpret_ca st<char*>(&temp ))[i] = buff[i];
The advantage of this is that it works on any size of unsigned long, just
gotta make sure the buffer is long enough.
The disadvantage of this is that it supposes that the external
representation corresponds exactly to the internal one. You're
"advantage" is actually a serious disadvantage. If the external
format is four bytes, you want to convert exactly four bytes, no
more no less. You don't want to suddenly start reading eight
bytes just because you upgraded your machine, when only four
bytes were read.

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

May 10 '07 #10

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

Similar topics

19
16815
by: Vincent | last post by:
Hi all, I want to convert a char (binary) to an unsigned long. How can I do this? Thanks, Vincent
44
12756
by: RB | last post by:
How to extract bytes from long, starting from the last byte? For example, I have a long number: 0x12345678 I need to represent it as the following bytes list: 0x78, 0x56, 0x34, 0x12 Thanks in advance, Rita
7
2155
by: bryan | last post by:
I think I'm missing something fundamental here. I'm trying to set an unsigned long value via a u_long pointer, however it coredumps everytime I get to that instruction. Here is a sample program that demonstrates the issue: --- snip --- #include <unistd.h> int main() { char buf;
36
5319
by: Digital Puer | last post by:
Hi, suppose I have an unsigned long long. I would like to extract the front 'n' bits of this value and convert them into an integer. For example, if I extract the first 3 bits, I would get an int between 0 and 7 (=2^3-1). Could someone please help out? I can assume the largest returned value fits in an int. Also, I'm on a big-endian PPC (AIX), in case that matters. Ideally, I'd like to implement a prototype like: int...
15
7003
by: thomas.mertes | last post by:
For a hash function I want to reinterpret the bits of a float expression as unsigned long. The normal cast (unsigned long) float_expression truncates the float to an (unsigned long) integer. But this is not the effect I want for a hash function. With unions my hash function can be implemented:
3
4073
by: wenmang | last post by:
Hi, I encountered a problem involving storage of unsigned long long. The requirement of incoming data field is an unsigned 64-bit integer, but on our system, due to lack of support of 64-bit integer from Oralce pro-C(it only supports 32-bit integer). We have to find a way to get around it. I am wondering whether there is other way to store big int in kind of 8-byte raw data and later convert it to 64-bit integer. Is the raw data has to...
1
8224
by: Jacek Dziedzic | last post by:
Hello! This is my first time dealing with Very Large Files. I have vector of strings representing numbers and I need to extract bytes in binary mode from a Large File that correspond to ranges specified by the strings. For example for an input of "0", "100", "500", "700" I need to create three files, the first would contain
107
26009
by: bmshivaraj | last post by:
Hi, Could any one tell me how to convert a unsigned long value into string (char *) ? In C++ there is a function _ultoa so wanted a similar one in C . Regards, Shivaraj
105
6223
by: Keith Thompson | last post by:
pereges <Broli00@gmail.comwrites: These types already have perfectly good names already. Why give them new ones? If you must rename them for some reason, use typedefs, not macros. --
0
9425
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
10228
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
10057
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
9869
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...
1
7415
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
6676
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();...
1
3970
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
3575
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2816
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.