473,770 Members | 5,842 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to concatinate 32bits of 4 bytes in a char array, and assigning to an int?

Hi:

Ok, I've just read in up to 65,535 bytes into a char array (using the
recvfrom socket API
call). So I have an array of 8 bit char's (char recvString[ ];).

Now, four (4) consecutive bytes somewhere within that array represent a
counter.

How can I take those 4 individual bytes, concatinate the 32bits that
make up those
4 bytes, and assign them to "unsigned int i;". In other words, those
32bits represent
an unsigned counter, and I need to transfer them out of the array, make
an integer out
of those 32bits (8x4) and assign them to "unsigned int i", so I can
then perform some
simple math.

I've tried various methods with no luck and my problem may be
big/little endian.

Does any have portable code snippes for doing this (that won't break
when the
sizeof something chages for example, etc).

Regards,
Noelle Milton Vega
nm****@Computin gArchitects.Com

Jun 8 '06 #1
9 2384
Noel Milton wrote:
Hi:

Ok, I've just read in up to 65,535 bytes into a char array (using the
recvfrom socket API
call). So I have an array of 8 bit char's (char recvString[ ];). I'd ask whence char recvString[] came, but I suspect it didn't come from
standard C.
Now, four (4) consecutive bytes somewhere within that array represent a
counter.

How can I take those 4 individual bytes, concatinate the 32bits that
make up those
4 bytes, and assign them to "unsigned int i;". In other words, those
32bits represent
an unsigned counter, and I need to transfer them out of the array, make
an integer out
of those 32bits (8x4) and assign them to "unsigned int i", so I can
then perform some
simple math.

I've tried various methods with no luck and my problem may be
big/little endian.

Does any have portable code snippes for doing this (that won't break
when the
sizeof something chages for example, etc).

Since representation can be many and varied, I think you're going to
have to cook from scratch. frank
Jun 8 '06 #2
Hello Frank:

You might be right. I've tried many (and I mean many) variations of the
following
where I altered the format part of the string, with no luck... but I
think

unsigned int i;
-or-
unsigned char intBits[4 or 5];
snprintf/sprintf(intBits , 4, "%02hhu%02hhu%0 2hhu%02hhu",
*(recvString + 10),
*(recvString + 11),
*(recvString + 12),
*(recvString + 13));

But it could be that 12 & 13 should come before 10 & 11 (big/little
endian) or
even 13/12/11/10 (the complete reverse).
In the case of using char intBits[], I then tried something like i =
(int) *intBits;
And all kinds of stuff.

Do you think bit shifting and masking approach is better (or someother
approach)?

Regards.

Frank Silvermann wrote:
Noel Milton wrote:
Hi:

Ok, I've just read in up to 65,535 bytes into a char array (using the
recvfrom socket API
call). So I have an array of 8 bit char's (char recvString[ ];).

I'd ask whence char recvString[] came, but I suspect it didn't come from
standard C.

Now, four (4) consecutive bytes somewhere within that array represent a
counter.

How can I take those 4 individual bytes, concatinate the 32bits that
make up those
4 bytes, and assign them to "unsigned int i;". In other words, those
32bits represent
an unsigned counter, and I need to transfer them out of the array, make
an integer out
of those 32bits (8x4) and assign them to "unsigned int i", so I can
then perform some
simple math.

I've tried various methods with no luck and my problem may be
big/little endian.

Does any have portable code snippes for doing this (that won't break
when the
sizeof something chages for example, etc).

Since representation can be many and varied, I think you're going to
have to cook from scratch. frank


Jun 8 '06 #3
Noel Milton wrote:
Hello Frank:

You might be right. I've tried many (and I mean many) variations of the
following
where I altered the format part of the string, with no luck... but I
think

unsigned int i;
-or-
unsigned char intBits[4 or 5];
snprintf/sprintf(intBits , 4, "%02hhu%02hhu%0 2hhu%02hhu",
*(recvString + 10),
*(recvString + 11),
*(recvString + 12),
*(recvString + 13));

But it could be that 12 & 13 should come before 10 & 11 (big/little
endian) or
even 13/12/11/10 (the complete reverse).
In the case of using char intBits[], I then tried something like i =
(int) *intBits;
And all kinds of stuff.

Do you think bit shifting and masking approach is better (or someother
approach)?


Oh, dear. Your sprintf would deposit DISPLAY characters
into your intBits[ ] array, but you want BINARY characters
exactly as they already are in recvString[ ].

Try something like this:

int i = ((recvString[10] * 256 + recvString[11]) * 256
+ recvString[12]) * 256 + recvString[13];
and juggle the subscripts until it's right.
--

Jun 8 '06 #4


Noel Milton wrote On 06/08/06 13:25,:
Hi:

Ok, I've just read in up to 65,535 bytes into a char array (using the
recvfrom socket API
call). So I have an array of 8 bit char's (char recvString[ ];).

Now, four (4) consecutive bytes somewhere within that array represent a
counter.

How can I take those 4 individual bytes, concatinate the 32bits that
make up those
4 bytes, and assign them to "unsigned int i;". In other words, those
32bits represent
an unsigned counter, and I need to transfer them out of the array, make
an integer out
of those 32bits (8x4) and assign them to "unsigned int i", so I can
then perform some
simple math.


First, use a buffer of `unsigned char' instead of
plain `char'. Plain `char' may be either signed or
unsigned at the implementation' s whim, and you don't
want negative byte values making things complicated.

Next, suppose that the four bytes of interest are
at positions [n] through [n+3]. If they are arranged in
big-endian order (most significant at [n]), use

i = 256u * 256u * 256u * buf[n]
+ 256u * 256u * buf[n+1]
+ 256u * buf[n+2]
+ buf[n+3];

If they are arranged in little-endian order (least
significant at [n]), turn the indices around and use

i = 256u * 256u * 256u * buf[n+3]
+ 256u * 256u * buf[n+2]
+ 256u * buf[n+1]
+ buf[n];

If they are arranged in some more exotic order (there
are 24 possibilities in all, and at least three have
actually been used), just multiply each byte's value
by the corresponding power of 256 -- just think of the
value as a four-digit number written in base 256, and
all should become clear.

There are, of course, many ways to write the expressions
above. The way I've chosen assumes an `unsigned int' of 32
or more bits, while C itself only promises 16 or more; you
could use 256ul throughout to change to `unsigned long'.
Also, the expressions above are careful to avoid potential
confusions between `int' and `unsigned int'; if you choose
to rewrite using shift operators, for example, be careful
about unintended promotions to signed `int'.

--
Er*********@sun .com

Jun 8 '06 #5
Thanks Bert... Love the "Oh dear" part LOL. I did try stripping '\0'
and other
artifacts, but, as you alluded, these are the annoyances with this
method.

Your proposal sounds better. In fact, I was going the take each 4bit
hex char and
perform hex to dec math to get the value (e.g. ((a1*16 + a2)*16 +
a3)*16 +a4 ...
and so on), but yours is better because its on a byte-by-byte
basis, versus on a 4 bit hex-by-hex basis, so half as many
calculations.

Btw... nice use, of algebraic precedence (always nice to see).

Regards
Oh, dear. Your sprintf would deposit DISPLAY characters
into your intBits[ ] array, but you want BINARY characters
exactly as they already are in recvString[ ].

Try something like this:

int i = ((recvString[10] * 256 + recvString[11]) * 256
+ recvString[12]) * 256 + recvString[13];

and juggle the subscripts until it's right.
--


Jun 8 '06 #6
Thaks Eric... your and Bert's examples (the same algorithmically ),
is what I was looking for. Appreciate the time for the lengthy
expansion Eric. Regards Bert/Eric.

Eric Sosman wrote:
Noel Milton wrote On 06/08/06 13:25,:
Hi:

Ok, I've just read in up to 65,535 bytes into a char array (using the
recvfrom socket API
call). So I have an array of 8 bit char's (char recvString[ ];).

Now, four (4) consecutive bytes somewhere within that array represent a
counter.

How can I take those 4 individual bytes, concatinate the 32bits that
make up those
4 bytes, and assign them to "unsigned int i;". In other words, those
32bits represent
an unsigned counter, and I need to transfer them out of the array, make
an integer out
of those 32bits (8x4) and assign them to "unsigned int i", so I can
then perform some
simple math.


First, use a buffer of `unsigned char' instead of
plain `char'. Plain `char' may be either signed or
unsigned at the implementation' s whim, and you don't
want negative byte values making things complicated.

Next, suppose that the four bytes of interest are
at positions [n] through [n+3]. If they are arranged in
big-endian order (most significant at [n]), use

i = 256u * 256u * 256u * buf[n]
+ 256u * 256u * buf[n+1]
+ 256u * buf[n+2]
+ buf[n+3];

If they are arranged in little-endian order (least
significant at [n]), turn the indices around and use

i = 256u * 256u * 256u * buf[n+3]
+ 256u * 256u * buf[n+2]
+ 256u * buf[n+1]
+ buf[n];

If they are arranged in some more exotic order (there
are 24 possibilities in all, and at least three have
actually been used), just multiply each byte's value
by the corresponding power of 256 -- just think of the
value as a four-digit number written in base 256, and
all should become clear.

There are, of course, many ways to write the expressions
above. The way I've chosen assumes an `unsigned int' of 32
or more bits, while C itself only promises 16 or more; you
could use 256ul throughout to change to `unsigned long'.
Also, the expressions above are careful to avoid potential
confusions between `int' and `unsigned int'; if you choose
to rewrite using shift operators, for example, be careful
about unintended promotions to signed `int'.

--
Er*********@sun .com


Jun 8 '06 #7
"Noel Milton" <nm****@Computi ngArchitects.Co m> writes:
Thaks Eric... your and Bert's examples (the same algorithmically ),
is what I was looking for. Appreciate the time for the lengthy
expansion Eric. Regards Bert/Eric.


Let me direct your attention to <http://www.caliburn.nl/topposting.html >.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Jun 8 '06 #8
Noel Milton wrote:

You might be right. I've tried many (and I mean many) variations
of the following where I altered the format part of the string,
with no luck... but I think

unsigned int i;
-or-
unsigned char intBits[4 or 5];

.... snip ...

Don't toppost. Your reply belongs after, or intermixed with, the
material to which you reply, after snipping anything not germane to
your reply.

--
"Our enemies are innovative and resourceful, and so are we.
They never stop thinking about new ways to harm our country
and our people, and neither do we." -- G. W. Bush.
"The people can always be brought to the bidding of the
leaders. All you have to do is tell them they are being
attacked and denounce the pacifists for lack of patriotism
and exposing the country to danger. It works the same way
in any country." --Hermann Goering.

Jun 8 '06 #9
Eric Sosman wrote:

Noel Milton wrote On 06/08/06 13:25,:
Hi:

[OP has 4 bytes and wants an int]
First, use a buffer of `unsigned char' instead of
plain `char'. Plain `char' may be either signed or
unsigned at the implementation' s whim, and you don't
want negative byte values making things complicated.

Next, suppose that the four bytes of interest are
at positions [n] through [n+3]. If they are arranged in
big-endian order (most significant at [n]), use

i = 256u * 256u * 256u * buf[n]
+ 256u * 256u * buf[n+1]
+ 256u * buf[n+2]
+ buf[n+3];

If they are arranged in little-endian order (least
significant at [n]), turn the indices around and use

i = 256u * 256u * 256u * buf[n+3]
+ 256u * 256u * buf[n+2]
+ 256u * buf[n+1]
+ buf[n];

If they are arranged in some more exotic order (there
are 24 possibilities in all, and at least three have
actually been used), just multiply each byte's value
by the corresponding power of 256 -- just think of the
value as a four-digit number written in base 256, and
all should become clear. 24 = 4!

There are, of course, many ways to write the expressions
above. The way I've chosen assumes an `unsigned int' of 32
or more bits, while C itself only promises 16 or more; you
could use 256ul throughout to change to `unsigned long'.
Also, the expressions above are careful to avoid potential
confusions between `int' and `unsigned int'; if you choose
to rewrite using shift operators, for example, be careful
about unintended promotions to signed `int'.

I see no a priori reason to think his bits were going to add up to a
byte in any meaningful way. There is no guarantee that the non Standard
methods will be common sensical in this respect. Your post is an
example of the type I print out and put into my notebook for hard-copy
perusal at the cafe. frank
Jun 8 '06 #10

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

Similar topics

5
6011
by: Jonathan Halterman | last post by:
I have a pointer to a buffer of bytes that I receive from a tcp stream that I would like to place into some kind of stream that can I can then use to serialize the data into into individual variables. I looked at the streambuf, istream, and strstream, and can't quite figure out a simple implementation for what I need. Given a pointer to a buffer of bytes, and the size of the bytes that I am concerned with, how can I get this into a...
16
2426
by: drj0nson | last post by:
What is the right way of creating a string/char array and assigning to a char* which is then used in a function call. Thought it would be quite nice to avoid a memory leakage /core dump. 1 Header with char* x 2 Class includes header 3 In Class member function I want to : a)conditionally create a string ie populate x
19
2871
by: becte | last post by:
I need to use three bytes to store four 6-bit integers (4 * 6 = 3 * 8) like this 11111122|22223333|33444444 Suppose the input is, int c1, c2, c3, c4, range 0 .. 2^6 -1 and the output is int o1,o2,o3, range 0 .. 2^8-1 How to do this in a clever way? (The 6 bits integers represent characters in range A-Z and 0-9)
7
1881
by: Frank | last post by:
Sorry that the question I posted few minutes ago didn't correctly describe the problem. So please ignore it. I repost the question as below: ============================================== I am developing an application on PPC405 (Walnut). But somehow in the string in the C function doesn't work. The code is as below: void example() {
19
2115
by: James Harris | last post by:
My K&R 2nd ed has in the Reference Manual appendix, A7.4.8 sizeof yields the number of BYTES required to store an object of the type of its operand. What happens if C is running on a machine that addresses larger words only? Shouldn't sizeof be defined to return the smallest number of 'storage units' required to store an object of the type of its operand? As a general point, is there a guide to what aspects of C would fail if run on a...
6
2197
by: lovecreatesbeauty | last post by:
/* It seems that when an int with width of four bytes is assigned to a one byte width char, the first three bytes from left to right are discarded and the rightest byte is assigned to that char. So, I can just assign an int to a char to retrieve the rightest byte of that int, and I also use this method plus right-shift operation to get the leftest byte of an int.
9
7633
by: rob.kirkpatrick | last post by:
Hello I need to populate an array of char arrays at run-time. A very simplifed version of the code is below. char ** list should contain cnt char arrays. The values of char ** list are set by the function foo(). A pointer to char ** list is passed to foo() as an argument. The problem is that when foo() returns, char ** list contains rubbish
9
10528
by: Peithon | last post by:
Hi, This is a very simple question but I couldn't find it in your FAQ. I'm using VC++ and compiling a C program, using the /TC flag. I've got a function for comparing two strings int strspcmp(const char * s1, const char * s2) {
90
7115
by: Martin Wells | last post by:
I have an array as follows: char unsigned data; I want to set every single bit in the array to 1. My initial thoughts were: memset(data, UCHAR_MAX, sizeof data); but then when I looked at the declaration for memset, I saw that the
0
9591
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10053
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...
1
10001
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
9867
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
8880
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...
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();...
0
5312
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
3969
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
3573
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.