Shorthand byte designation in C / C ++?

It has been a while since I programmed C / C ++. For my life I cannot remember (or find on Google) how to do this. I thought there was a shorthand way of writing a repeating string of bytes, for example:

0x00 => 0x00000000 0xFF => 0xFFFFFFFF 0xCD => 0xCDCDCDCD 

So for example, if I declare

 int x = 0xCD; printf("%d", x) // prints "3452816845", not "205". 

Without the use of bit shifts (i.e., the preprocessor processes it). I've gone mad? PS I am using Microsoft Visual C ++ 2010

+6
source share
7 answers

The easiest way:

 0x1010101u * x 

I can not imagine a single syntax that could be simpler or more understandable ...

Edit: I see that you want it to work for arbitrary types. Since this only makes sense for unsigned types, I assume that you are using an unsigned type. Then try

 #define REPB(t, x) ((t)-1/255 * (x)) 
+13
source

By default, C. is nothing like this. There is something similar in CSS (color #123 expands to #112233 ), but it's completely different. :)

You can write a macro to do this for you, for example:

 #define REPEAT_BYTE(x) ((x) | ((x) << 8) | ((x) << 16) | ((x) << 24)) ... int x = REPEAT_BYTE(0xcd); 
+8
source

If you do not write your own macro, this is not possible. How would he know how long to repeat? 0xAB can mean 0xABABABABABABABABABABAB for everything he knows (using the suggested idea).

+2
source

There is no such shorthand. 0x00 is the same as 0. 0xFF is the same as 0x000000FF.

+2
source

Nope. But you can use memset:

 int x; memset(&x, 0xCD, sizeof(x)); 

And you can make a macro of this:

 #define INITVAR(var, value) memset(&(var), (int)(value), sizeof(var)) int x; INITVAR(x, 0xCD); 
+2
source

You can use some pattern tricks:

 #include <iostream> #include <climits> using namespace std; template<typename T, unsigned char Pattern, unsigned int N=sizeof(T)> struct FillInt { static const T Value=((T)Pattern)<<((N-1)*CHAR_BIT) | FillInt<T, Pattern, N-1>::Value; }; template<typename T, unsigned char Pattern> struct FillInt<T, Pattern, 0> { static const T Value=0; }; int main() { cout<<hex<<FillInt<unsigned int, 0xdc>::Value<<endl; // outputs dcdcdcdc on 32 bit machines } 

which automatically adapts to the integral type passed as the first argument and is fully resolved at compile time, but this is just for fun, I donโ€™t think I would use such a thing in real code.

+1
source

You can use concatenation of the preprocessor token:

 #include <stdio.h> #define multi4(a) (0x##a##a##a##a) int main() { int a = multi4(cd); printf("0x%x\n", a); return 0; } 

Result:

 0xcdcdcdcd 

Of course, you need to create a new macro every time you want to create a โ€œgeneratorโ€ with a different number of repetitions.

+1
source

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


All Articles