How to get integer char value in C ++?

I want to take the value stored in a 32-bit unsigned int, put it in four characters, and then store the integer value of each of these characters in a string.

I think the first part will look like this:

char a = orig << 8; char b = orig << 8; char c = orig << 8; char d = orig << 8; 
+4
source share
5 answers

If you really want to extract individual bytes first:

 unsigned char a = orig & 0xff; unsigned char b = (orig >> 8) & 0xff; unsigned char c = (orig >> 16) & 0xff; unsigned char d = (orig >> 24) & 0xff; 

Or:

 unsigned char *chars = (unsigned char *)(&orig); unsigned char a = chars[0]; unsigned char b = chars[1]; unsigned char c = chars[2]; unsigned char d = chars[3]; 

Or use the union of unsigned long and four chars:

 union charSplitter { struct { unsigned char a, b, c, d; } charValues; unsigned int intValue; }; charSplitter splitter; splitter.intValue = orig; // splitter.charValues.a will give you first byte etc. 

Update: as Friol pointed out, solutions 2 and 3 are not agnostic; which bytes a , b , c and d represent a dependency on the CPU architecture.

+10
source

Let's say "orig" is a 32-bit variable containing your value.

I assume you want to do something like this:

 unsigned char byte1=orig&0xff; unsigned char byte2=(orig>>8)&0xff; unsigned char byte3=(orig>>16)&0xff; unsigned char byte4=(orig>>24)&0xff; char myString[256]; sprintf(myString,"%x %x %x %x",byte1,byte2,byte3,byte4); 

I am not sure that this is always true. (Editing: indeed, it is correct with respect to the end, since bitrate operations should not be subject to endianness)

Hope this helps.

+10
source

Use union . (As requested by the sample program here.)

  #include <<iostream>> #include <<stdio.h>> using namespace std; union myunion { struct chars { unsigned char d, c, b, a; } mychars; unsigned int myint; }; int main(void) { myunion u; u.myint = 0x41424344; cout << "a = " << u.mychars.a << endl; cout << "b = " << u.mychars.b << endl; cout << "c = " << u.mychars.c << endl; cout << "d = " << u.mychars.d << endl; } 

As James said, this is platform specific.

+4
source

Not really:

 char a = orig & 0xff; orig >>= 8; char b = orig & 0xff; orig >>= 8; char c = orig & 0xff; orig >>= 8; char d = orig & 0xff; 

Not quite sure what you mean by "store the integer values ​​of each of these values ​​in a string. Would you like to turn 0x10111213 into "16 17 18 19" , or what?

+1
source

For hexadecimal:

 sprintf(buffer, "%lX", orig); 

For decimal:

 sprintf(buffer, "%ld", orig); 

Use snprintf to avoid buffer overflows.

0
source

Source: https://habr.com/ru/post/1277542/


All Articles