473,847 Members | 1,855 Online

# Accessing individual bytes of an integer

Hello!

I want to work with individual bytes of integers. I know that ints are
32-bit and will always be. Sometimes I want to work with the entire
32-bits, and other times I want to modify just the first 8-bits for
example. For me, I think it would be best if I can declare the 32-bits
like this:

unsigned char bits[4];

When I want to treat this as a 32-bits integer, can I do something
like this?

unsigned int bits32 = *((unsigned int*)bits);

I'm unsure of the syntax. I don't need to work in-place so to speak. It is
fine to work with a copy.

Thanks in advance!

--
Daniel

Jul 23 '05 #1
27 4258
"Daniel Lidström" <so*****@micros oft.com> wrote in message
news:pa******** *************** *****@microsoft .com...
When I want to treat this as a 32-bits integer, can I do something
like this?

unsigned int bits32 = *((unsigned int*)bits);

Yes you can, but you have absolutely no assurance as to what the results
will be :-)

What's wrong with

(bits>>n) & 0xff

where n is 0, 8, 16, or 24?
Jul 23 '05 #2

"Daniel Lidström" <so*****@micros oft.com> ????
news:pa******** *************** *****@microsoft .com...
Hello!

I want to work with individual bytes of integers. I know that ints are
32-bit and will always be. Sometimes I want to work with the entire
32-bits, and other times I want to modify just the first 8-bits for
example. For me, I think it would be best if I can declare the 32-bits
like this:

unsigned char bits[4];

When I want to treat this as a 32-bits integer, can I do something
like this?

unsigned int bits32 = *((unsigned int*)bits);

I'm unsure of the syntax. I don't need to work in-place so to speak. It is
fine to work with a copy.

Thanks in advance!

--
Daniel

Unconsidering the byte sequence, you are correct.
A better way is using a union like:
union xxx
{
unsigned char bits[4];
unsigned int i;
};
Jul 23 '05 #3
MatrixV wrote:
"Daniel Lidström" <so*****@micros oft.com> ????
news:pa******** *************** *****@microsoft .com...
Hello!

I want to work with individual bytes of integers. I know that ints are
32-bit and will always be. Sometimes I want to work with the entire
32-bits, and other times I want to modify just the first 8-bits for
example. For me, I think it would be best if I can declare the 32-bits
like this:

unsigned char bits[4];

When I want to treat this as a 32-bits integer, can I do something
like this?

unsigned int bits32 = *((unsigned int*)bits);

I'm unsure of the syntax. I don't need to work in-place so to speak. It is
fine to work with a copy.

Thanks in advance!

--
Daniel

Unconsidering the byte sequence, you are correct.
A better way is using a union like:
union xxx
{
unsigned char bits[4];
unsigned int i;
};

How about this:
union xxx
{
unsigned char bytes[sizeof(unsigned int))];
unsigned int i;
};
This makes no assumptions about how many bytes are
in an integer.
--
Thomas Matthews

C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.l earn.c-c++ faq:
http://www.comeaucomputing.com/learn/faq/
Other sites:
http://www.josuttis.com -- C++ STL Library book
http://www.sgi.com/tech/stl -- Standard Template Library

Jul 23 '05 #4
"MatrixV" <tr******@kcoll ege.com> wrote in message
news:37******** *****@individua l.net...
Unconsidering the byte sequence, you are correct.
A better way is using a union like:
union xxx
{
unsigned char bits[4];
unsigned int i;
};

Not really. When you use a union, you have no assurance about the effect
that giving a value to one member of a union will have on other members.
Jul 23 '05 #5
MatrixV wrote:
"Daniel Lidström" <so*****@micros oft.com> ????

I want to work with individual bytes of integers. I know that ints are 32-bit and will always be. Sometimes I want to work with the entire
32-bits, and other times I want to modify just the first 8-bits for
example. For me, I think it would be best if I can declare the 32-bits like this:

unsigned char bits[4];

When I want to treat this as a 32-bits integer, can I do something
like this?

unsigned int bits32 = *((unsigned int*)bits);
Bad - if 'bits' is not correctly aligned for an int, then
you have undefined behaviour.
I'm unsure of the syntax. I don't need to work in-place so to speak. It is fine to work with a copy.

You can work in-place with:
unsigned int bits32;
and then to access the chars:
((unsigned char *)&bits32)[0]
etc. Note that the contents of the chars could be anything
(eg. big endian, little endian, or something more exotic),
and if you modify one of those chars then you aren't guaranteed
to have anything sensible left in bits32.

If you don't want to work in-place then you could memcpy
between the int and the char (with the same caveats I mentioned
already).

To work portably (assuming a 32-bit int and 8-bit char),
you can use bit-shifts and masks to extract the four bytes
and replace them. A good compiler would optimise this code
into a single instruction, if it could.
Unconsidering the byte sequence, you are correct.
A better way is using a union like:
union xxx
{
unsigned char bits[4];
unsigned int i;
};

Undefined behaviour if you access a member of a union that
wasn't the one you just set.

Jul 23 '05 #6
On 2005-02-17 15:38:50 -0500, "Andrew Koenig" <ar*@acm.org> said:
"MatrixV" <tr******@kcoll ege.com> wrote in message
news:37******** *****@individua l.net...
Unconsidering the byte sequence, you are correct.
A better way is using a union like:
union xxx
{
unsigned char bits[4];
unsigned int i;
};

Not really. When you use a union, you have no assurance about the
effect that giving a value to one member of a union will have on other
members.

You do when one of them is an array of unsigned char.

--
Clark S. Cox, III
cl*******@gmail .com

Jul 23 '05 #7
Daniel Lidström wrote:
Hello!

I want to work with individual bytes of integers. I know that ints are
32-bit and will always be. Sometimes I want to work with the entire
32-bits, and other times I want to modify just the first 8-bits for
example. For me, I think it would be best if I can declare the 32-bits
like this:

unsigned char bits[4];

When I want to treat this as a 32-bits integer, can I do something
like this?

unsigned int bits32 = *((unsigned int*)bits);

Yes but not like this because array bits is not initialised.
I'm unsure of the syntax. I don't need to work in-place so to speak. It is
fine to work with a copy.

What you can do is read an unsigned int or any other POD type as a
sequence of unsigned chars (or plain chars) - that is bytes, copy it
byte by byte to another unsigned char sequence (which includes possible
padding bits), and deal the new char sequence as another unsigned int.
The following example uses an int and is portable:
#include <iostream>

int main()
{
int integer=0;

unsigned char *puc= reinterpret_cas t<unsigned char *>(&integer);
unsigned char otherInt[sizeof(integer)];

// Read integer byte by byte and copy it to otherInt
for(unsigned i=0; i<sizeof(intege r); ++i)
otherInt[i]= puc[i];
// We treat the new unsigned char sequence as an int
int *p= reinterpret_cas t<int *>(otherInt);

// Assign another value to the integer otherInt!
*p=7;

std::cout<<*p<< "\n";
}

--
Ioannis Vranos

http://www23.brinkster.com/noicys
Jul 23 '05 #8
On Thu, 17 Feb 2005 19:16:24 +0100, Daniel Lidström
<so*****@micros oft.com> wrote in comp.lang.c++:
Hello!

I want to work with individual bytes of integers. I know that ints are
32-bit and will always be.

No, you don't. You just think you do. But you are mistaken.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.l earn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Jul 23 '05 #9
>> Not really. When you use a union, you have no assurance about the effect
that giving a value to one member of a union will have on other members.
You do when one of them is an array of unsigned char.

Can you show me where in the C++ standard it says that? The text that I
think is relevant can be found in subclause 9.5:

In a union, at most one of the data members can be active at any time, that
is, the value of at most one of the data members can be stored in a union at
any time. [Note: one special guarantee is made in order to simplify the use
of unions: If a POD-union contains several POD-structs that share a common
initial sequence (9.2), and if an object of this POD-union type contains one
of the POD-structs, it is permitted to inspect the common initial sequence
of any of POD-struct members; see 9.2. ]

I think that "Only one of the data members can be active at any time" is
pretty clear, and the one exception to that rule says nothing about array of
unsigned character.

Jul 23 '05 #10

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

### Similar topics

 1 2078 by: J. Campbell | last post by: I have a feeling that I'm doing things all ass-backwards (again ;-), and would like some advice. What I want to do is: put some data to memory and then access that memory space as an array of data-types of my choosing (eg an array of char, short, or int). The application has to do with generating checksum-type values for files or strings, so speed is important, as I just want to quickly get this value then move on to the next task. As... 1 3378 by: Erinys | last post by: Hi, I need to access the individual bytes in a string in my javascript function. If the characters in the string were all ascii characters then there would not be a problem, however in my case the string may contain ISO-2022-JP or UTF8 characters, so these characters may be larger than 1 byte each. Is there a way to extract the individual bytes, or convert a string to an array of bytes in javascript? 25 6775 by: TK | last post by: I'm used to programming in c or c++ in which my problem is simple. I want to be able to enter a value on a page (like 3.2), and then read it as a 32-bit float and break it into it's individual bytes. I've tried using bitwise operators, but they seem to convert the value into an integer first, and i've tried using the toString() method to convert it into a hex value so i can parse it, but that also seems to first convert it into an... 10 1644 by: Christian Christmann | last post by: Hi, I'm wondering if my small example is not "dangerous": #define SIZE 10 char global; char* globalPtr = global; int main() 1 1141 by: Christian Heimes | last post by: Peter Robinson schrieb: As John already said: UTF-8 ain't unicode. UTF-8 is an encoding similar to ASCII or Latin-1 but different in its inner workings. A single character may be encoded by up to 6 bytes. I highly recommend Joel's article on unicode: The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) 16 6807 by: s0suk3 | last post by: This code #include int main(void) { int hello = {'h', 'e', 'l', 'l', 'o'}; char *p = (void *) hello; for (size_t i = 0; i < sizeof(hello); ++i) { 0 9881 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 10982 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 10645 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 10706 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,... 1 7880 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 7053 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 5718 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 4523 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 3 3160 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.