A sequence of bitwise of operation on bits grouped two by two - bit-manipulation

I am looking for a sequence of bitwise operations that has the
following property:
| 00 01 10 11
---|---------------
00 | 00
01 | 01 01
10 | 00 01 00
11 | 00 01 11 11
The groups of bits operated upon are on the vertical
and horizontal margins, the result matrix is symmetrical.

The following code implements what you would like in C/C++.
#include<stdio.h>
int main(void)
{
int i, j;
for(i=0; i<4; i++)
{
for(j=0; j<4; j++)
{
int x = i&j&(i|j)<<1|(i|j)&(~((i^j)&(i^j)>>1)|(i>>1^i))&1;
printf("%d%d ", x>>1, x&1);
}
printf("\n");
}
return 0;
}

Related

C++ structure/array initialization

I have a C++ array or structure initialization issue that I have not been able to resolve.
I have a 4-level nested structure. Each level is actually the same 48 bytes wrapped in the structure next level up. The issue is when the structure is initialized and declared as a scalar value, it is correctly initialized with the provided values. However, when it is declared as a single element array, all 48 bytes become zeros, as shown below. Unfortunately the structures are too complicated to be pasted here.
If I define 4 simple structures, one containing another, with the innermost one containing the same 12 unsigned integers, then it is initialized correctly, even if it is declared in an array.
Has anyone experienced similar issues? What am I missing? What compiler flags, options, etc could lead to such a problem? Appreciate any comments and help.
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "bls12_381/fq.hpp"
static constexpr embedded_pairing::bls12_381::Fq scalar = {
{{{.std_words = {0x1c7238e5, 0xcf1c38e3, 0x786f0c70, 0x1616ec6e, 0x3a6691ae, 0x21537e29,
0x4d9e82ef, 0xa628f1cb, 0x2e5a7ddf, 0xa68a205b, 0x47085aba, 0xcd91de45}}}}
};
static constexpr embedded_pairing::bls12_381::Fq array[1] = {
{{{{.std_words = {0x1c7238e5, 0xcf1c38e3, 0x786f0c70, 0x1616ec6e, 0x3a6691ae, 0x21537e29,
0x4d9e82ef, 0xa628f1cb, 0x2e5a7ddf, 0xa68a205b, 0x47085aba, 0xcd91de45}}}}}
};
void print_struct(const char *title, const uint8_t *cbuf, int len)
{
printf("\n");
printf("[%s] %d\n", title, len);
for (int i = 0; i < len; i++) {
if (i % 30 == 0 && i != 0)
printf("\n");
else if ((i % 10 == 0 || i % 20 == 0) && i != 0)
printf(" ");
printf("%02X ", cbuf[i]);
}
printf("\n");
}
void run_tests()
{
print_struct("scalar", (const uint8_t *) &scalar, sizeof(scalar));
print_struct("array", (const uint8_t *) &array[0], sizeof(array[0]));
}
[scalar] 48
E5 38 72 1C E3 38 1C CF 70 0C 6F 78 6E EC 16 16 AE 91 66 3A 29 7E 53 21 EF 82 9E 4D CB F1
28 A6 DF 7D 5A 2E 5B 20 8A A6 BA 5A 08 47 45 DE 91 CD
[array] 48
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
I've just narrowed down the example.
The following is a complete and standalone example. I also forgot to mention that the initialization on Linux using g++ 9.3.0, -std=c++17, gets the expected results of all FF's. However, on an embedded device, the inherited structure gets all 0's.
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct Data {
uint32_t words;
};
struct Overlay {
Data val;
};
struct Inherit : Data {
};
static Overlay overlay[1] = {
{{.words = 0xffffffff}}
};
static Inherit inherit[1] = {
{{.words = 0xffffffff}}
};
void print_struct(const char *title, const uint8_t *cbuf, int len)
{
printf("[%s] %d\n", title, len);
for (int i = 0; i < len; i++) {
printf("%02X ", cbuf[i]);
}
printf("\n");
}
int main()
{
print_struct("overlay", (const uint8_t *) &overlay[0], sizeof(overlay[0])); // FF FF FF FF
print_struct("inherit", (const uint8_t *) &inherit[0], sizeof(inherit[0])); // 00 00 00 00 <-- incorrect?
return 0;
}

Lottery simulator is returning garbage values and not the users lotto numbers and the winning numbers

I've been writing this c++ lotto simulator and im trying to get it to display the users lotto numbers (userNums array), the winning numbers that are randomly generated and inserted into an array (pBallDrawing) and then your winnings but when i try to output the two arrays using a for loop i just get garbage values (-84792048 that kind of thing) or the last value of the array.
I believe it goes wrong around the duplicate tests for both arrays but i dont know how exactly. I've tried mixing it around but then it just displays the last inputted value.
EDIT: ok so ive narrowed down the problem to these functions. I have these functions set in a loop inside main. Thank you for the suggestions about using things like std::shuffle and shoring up my output but im in a beginners class and my professor hasn't taught use that so im pretty sure i'd get knocked off points for using 'shortcuts' like shuffle.
void userPBInput(int &num) {
cout << "Please enter 5 unique numbers you would like to use for the lottery--> ";
cin >> num;
}
//*************userPBInputTest********************************
//Description: tests the userNums to make sure they are destinct and within range.
//Pre: recives the userNums array and num cin value from the preveious function.
//Post: will test the array and then pass it back to userPBInput.
//************************************************************
void userPBInputTest(int num, int userNums[BALLCNT]) {
for (int r = 0; r < BALLCNT - 2; r++) {
while (num<MIN || num>MAX) {
cout << "Error. Please enter a number within 1 and 69 --> ";
cin >> num;
}
while (num == userNums[r]) {
cout << "Error. Please enter a new number that you haven't entered already--> ";
cin >> num;
}
userNums[r] = num;
}
}
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
const int BALLCNT = 6;
const int REDBALL = 5;
const int MAX = 69;
const int MIN = 1;
const int RMAX = 26;
void userPBInput (int &num);
void userPBInputTest(int num, int userNums[BALLCNT]);
void redBall(int userNums[BALLCNT]);
void rngPBall(int drawing);
void rngPBallTest(int drawing, int ballDrawing[BALLCNT]);
void redRngPBall(int ballDrawing[BALLCNT]);
void matchCounter(int userNums[BALLCNT], int ballDrawing[BALLCNT]);
void winnings(int match, bool redMatch);
int main() {
srand(time(NULL));
int userNums[BALLCNT]; //users lotto numbers
int ballDrawing[BALLCNT]; // the winning numbers
int num = 0; // secondary value to validate users numbers for range and duplicates
int drawing = 0; // same as previous but with the winning numbers (duplicate only not range)
int match = 0; //will count how many white ball matches between the winning and the users numbers
bool redMatch = false; //tracks if you get a match with the red lotto ball.
for (int k = 0; k < BALLCNT - 1; k++) { //puts the functions into loop so you can enter 5 numbers and have them tested
userPBInput(num);
userPBInputTest(num, userNums);
}
redBall(userNums); //allows you to enter the redball number in the 6th element of the array
for (int g = 0; g < BALLCNT - 1; g++) { //loop to generate and test 5 numbers
rngPBall(drawing); //Where the user inputs their lotto numbers
rngPBallTest(drawing, ballDrawing); // the teest
}
redRngPBall(ballDrawing);
matchCounter(userNums, ballDrawing);
winnings(match, redMatch);
}
//*******************userPBInput*****************************
//Description: Will accept 5 numbers and the 6th red number from the user.
//Pre: receives num value for comparison in
//post: will be filled with numbers as the userPBInputTest tests to make sure that they are within range and are distinct and then passed to the decideWinnings function.
//****************************************************
void userPBInput(int &num) {
cout << "Please enter 5 unique numbers you would like to use for the lottery--> ";
cin >> num;
}
//*************userPBInputTest********************************
//Description: tests the userNums to make sure they are destinct and within range.
//Pre: recives the userNums array and num cin value from the preveious function.
//Post: will test the array and then pass it back to userPBInput.
//************************************************************
void userPBInputTest(int num, int userNums[BALLCNT] ){
for (int r = 0; r < BALLCNT - 1; r++) {
while (num<MIN || num>MAX) {
cout << "Error. Please enter a number within 1 and 69 --> ";
cin >> num;
}
while (num == userNums[r]) {
cout << "Error. Please enter a new number that you haven't entered already--> ";
cin >> num;
}
userNums[r] = num;
}
}
//*************redBall*********************
//Description: Asks the user for what value they'd like for their red powerball
//Pre: recieves empty int redB value
//post: will pass redB on to the winnings decision function to be compared with the
//randomly generated red ball value
//**************************************
void redBall(int userNums[BALLCNT]) {
cout << " And what would you like for your powerball? (aka the redball)-->";
cin >> userNums[REDBALL];
while ( userNums[REDBALL]> MAX || userNums[REDBALL] < MIN) {
cout << " The red ball need to be within 1 and 26. Try again--> ";
cin >> userNums[REDBALL];
}
}
//**********rngPBall******************************
//Description: Will generate 5 random numbers for the simulated ball drawing and one value for the redBall
//Pre: Will recieve the array meant for the lotto drawing
//Post: will be passed to the test function to make sure they are unique and within range and then passed to the winnings calculator
//*************************************************
void rngPBall(int drawing) {
drawing = MIN + rand() % MAX;
}
//**********rngPBallTest********************
//Description: will test the randomly generated numbers for duplicates and make a new number if so
//Pre: Recieves drawing value with RNG number and the winning numbers array
//post: will pass on fully tested array to main and to the winnings calculator
//******************************************
void rngPBallTest(int drawing, int ballDrawing[BALLCNT]) {
for (int e = 0; e < BALLCNT - 1; e++) { //to test the winning numbers for duplicates
while (drawing == ballDrawing[e])
drawing = MIN + rand() % MAX;
ballDrawing[e] = drawing; //assigns the value of drawing to its place in the ballDrawing Array
}
}
//***********redRngPBall********************************************
// Description: to generate a winning number for the last value in the array, to represent the red ball
//Pre: recieves ballDrawing Array and fills the last element with the red ball drawing
//Post: will pass full array to winnings calculator
//******************************************************************
void redRngPBall(int ballDrawing[BALLCNT]){
ballDrawing[REDBALL] = MIN + rand() % RMAX; //Generates a number for the element #6
}
//**************matchCounter***************************************
// Description: will test each element of both arrays against eachother and track the amount of matches you have and if the
// red number matches.
//Pre: Recieves both users array and the randomly generated array .
//Post: will pass the match/redmatch ints to int winnings.
void matchCounter(int userNums[BALLCNT], int ballDrawing[BALLCNT]) {
int match = 0; //tracks how many matches you get
bool redMatch = false; //since you either have a match or you dont, made it a bool
for (int v = 0; v < BALLCNT - 1; v++) //user/winning match counting loop
while (userNums[v] == ballDrawing[v])
match++;
if (userNums[6] == ballDrawing[6]) //boolean decision.
redMatch = true;
}
//***************winnings********************************************
//Description: Will decide what your winnings are based on if the red powerball matches or not and how many white matches you get
//Pre: recieves the match int and redMatch bool
//post: will cout and return your winnings
//********************************************************************
void winnings(int match, bool redMatch) {
int winnings = 0
; switch (match) { //will decide what you win based on how many matches you get .
case 5: if (redMatch == true)
cout << "YOUVE JUST WON THE JACKPOT";
else
winnings = 1000000;
break;
case 4: if (redMatch == true)
winnings = 50000;
else
winnings = 100;
break;
case 3: if (redMatch == true)
winnings = 100;
else
winnings = 7;
break;
case 2:if (redMatch == true)
winnings = 7;
break;
case 1: if (redMatch == true)
winnings = 4;
break;
default: winnings = 4;
}
cout << " You win $" << winnings<<"."; //displays what you won.
}
I need it to be able to display the 6 numbers of both arrays, but just get garbage values
apologies if this is too much code but i didn't want to leave out any context.
You're accessing out of range on line 151
if (userNums[6] == ballDrawing[6])
BALLCNT is 6 which means that index 5 is highest numbered index that is valid
Here's the output when compiling with -fsanitize=address in clang - it tells you exactly where the problem is and what the problem is:
==27179==ERROR: AddressSanitizer: stack-buffer-overflow on address 0x7ffee1d64a58 at pc 0x00010de9d2ea bp 0x7ffee1d649a0 sp 0x7ffee1d64998
READ of size 4 at 0x7ffee1d64a58 thread T0
#0 0x10de9d2e9 in matchCounter(int*, int*) deleteme.cpp:151
#1 0x10de9c863 in main deleteme.cpp:43
#2 0x7fff6707f014 in start (libdyld.dylib:x86_64+0x1014)
Address 0x7ffee1d64a58 is located in stack of thread T0 at offset 56 in frame
#0 0x10de9c5ef in main deleteme.cpp:24
This frame has 3 object(s):
[32, 56) 'userNums' (line 26) <== Memory access at offset 56 overflows this variable
[96, 120) 'ballDrawing' (line 27)
[160, 164) 'num' (line 28)
HINT: this may be a false positive if your program uses some custom stack unwind mechanism or swapcontext
(longjmp and C++ exceptions *are* supported)
SUMMARY: AddressSanitizer: stack-buffer-overflow deleteme.cpp:151 in matchCounter(int*, int*)
Shadow bytes around the buggy address:
0x1fffdc3ac8f0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x1fffdc3ac900: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x1fffdc3ac910: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x1fffdc3ac920: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x1fffdc3ac930: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
=>0x1fffdc3ac940: 00 00 00 00 f1 f1 f1 f1 00 00 00[f2]f2 f2 f2 f2
0x1fffdc3ac950: 00 00 00 f2 f2 f2 f2 f2 04 f3 f3 f3 00 00 00 00
0x1fffdc3ac960: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x1fffdc3ac970: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x1fffdc3ac980: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x1fffdc3ac990: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
Shadow byte legend (one shadow byte represents 8 application bytes):
Addressable: 00
Partially addressable: 01 02 03 04 05 06 07
Heap left redzone: fa
Freed heap region: fd
Stack left redzone: f1
Stack mid redzone: f2
Stack right redzone: f3
Stack after return: f5
Stack use after scope: f8
Global redzone: f9
Global init order: f6
Poisoned by user: f7
Container overflow: fc
Array cookie: ac
Intra object redzone: bb
ASan internal: fe
Left alloca redzone: ca
Right alloca redzone: cb
==27179==ABORTING
Abort trap: 6

C++ cast and write unsigned int with value 10 gives 5 bytes

The following code leads to a binary file, which as an additional byte in front of the representation of the value 10.
int main()
{
unsigned int data0 = 8;
unsigned int data1 = 9;
unsigned int data2 = 10;
unsigned int data3 = 11;
std::ofstream file("test.bin", std::ios_base::out, std::ios_base::binary);
file.write(reinterpret_cast<char*>(&data0), sizeof(data0));
file.write(reinterpret_cast<char*>(&data1), sizeof(data1));
file.write(reinterpret_cast<char*>(&data2), sizeof(data2));
file.write(reinterpret_cast<char*>(&data3), sizeof(data3));
file.close();
return 0;
}
Here's what the hexdump of the file looks like:
08 00 00 00 09 00 00 00 0D 0A 00 00 00 0B 00 00 00
| 8 -> OK | 9 -> OK |??| 10 -> OK | 11 -> OK
What's going on here with the byte in front of the 10?
std::ofstream file("test.bin", std::ios_base::out, std::ios_base::binary);
should be
std::ofstream file("test.bin", std::ios_base::out | std::ios_base::binary);
Credit goes to user4581301. See the comments of the question.

Why isn't memset assigning 1? [duplicate]

This question already has answers here:
Why is memset() incorrectly initializing int?
(9 answers)
Closed 6 years ago.
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;
int color[1001][1001];
int main() {
int i, j;
memset(color, 1, sizeof(color[0][0]) * 2 * 2);
for(i = 0; i < 4; i++) {
for(j = 0; j < 4; j++) {
printf("%d ", color[i][j]);
}
printf("\n");
}
printf("\n");
return 0;
}
output:
16843009 16843009 16843009 16843009
0 0 0 0
0 0 0 0
0 0 0 0
Why isn't it assigning 1? Why didn't it print 1 instead of 16843009 ? How can i assign integer 1?
But if i write memset(color, 0, sizeof(color[0][0]) * 2 * 2); Then the output:
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
Why is this?
Any answer will be highly appreciated. Thanks in advance.
Because memset sets each byte to 1.
So if int is four bytes (32 bits, what it most commonly is) then you set each element to 0x01010101.
Read more in this memset reference page.
For a more C++-ish solution I suggest using std::fill:
std::fill(&color[0][0], &color[0][0] + sizeof(color) / sizeof(color[0][0]), 1);
That will set all elements to 1.
A third option is to use std::array instead, and its fill member function:
std::array<std::array<int, 1001>, 1001> color;
...
for (auto& inner : color)
{
inner.fill(1);
}
Manpage :
#include <string.h>
void *memset(void *s, int c, size_t n)
The memset() function fills the first n bytes of the memory area pointed to by s with the constant byte c.
Therefore, memset can't be used to initialize int array with 1 because if int is represented by 4 bytes, then it will initialize each bytes with 1.
16843009 is equivalent to 0x01010101. Each of 4 bytes are initialized with 01.
Using memset, an array of int can only be initialised with 0 or -1 because 0 and -1 both have all bits 0 and 1 respectively in two's complement binary representation regardless of the size of int data type.
memset() will write the specified value to every byte in the range, so if int is 4-byte long, the value will be 0x01010101, not 1.
To assign integer 1, assign integer 1.
for (i = 0; i < (int)(sizeof(color)/sizeof(*color)); i++) {
for (j = 0; j < (int)(sizeof(color[i])/sizeof(*color[i])); j++) {
color[i][j] = 1;
}
}
memset() is setting your memory 8-Bit aligned to the value you chose, which is 1. But for your array color[][] you declared the 32-Bit datatype int, which has four bytes. So what memset() does is to set each of this four bytes to the value 1.
This also explains your result: 16843009d = 0x01010101.
If you have a look at your memory:
memset() to 1:
//.color[0][0].||..color[0][1]...||..color[0][2]...||..color[0][3]..
01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01
//.color[1][0].||..color[1][1]...||..color[1][2]...||..color[1][3]..
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
//.color[2][0].||..color[2][1]...||..color[2][2]...||..color[2][3]..
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
//.color[3][0].||..color[3][1]...||..color[3][2]...||..color[3][3]..
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
memset() to 0:
//.color[0][0].||..color[0][1]...||..color[0][2]...||..color[0][3]..
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
//.color[1][0].||..color[1][1]...||..color[1][2]...||..color[1][3]..
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
//.color[2][0].||..color[2][1]...||..color[2][2]...||..color[2][3]..
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
//.color[3][0].||..color[3][1]...||..color[3][2]...||..color[3][3]..
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
If you are calling memset() with the value 0 then you get a 32 Bit int value = 0x00000000 = 0d.
Note:
If you want to set your whole array to a value use the following line:
memset(color, 1, sizeof(color));
Then your array looks the following:
1010101 1010101 1010101 1010101
1010101 1010101 1010101 1010101
1010101 1010101 1010101 1010101
1010101 1010101 1010101 1010101
View the code here[^].

vector or array value insertion

I have a variable
long long int alpha;
This alpha is basically 8 bytes
but I wish the byte size can be decided dynamically by input to the function.
So that it could be inserted to char* array.
If there is a function
int putInput(int sizeOfAlpha){
long long int alpha;
char* beta = (char*)malloc(128);
for(int i = 0 ; i < 128 ; i++){
... alpha calculation ...
beta[i*sizeOfAlpha] = alpha; // This is also wrong
}
}
Then the size of alpha has to be modified by sizeOfAlpha
For instance if sizeOfAlpha is 2 in decimal,
and if alpha is 0x00 00 00 00 00 00 04 20 in hex,
and if i is 0 ,
then beta[0] should be 04 and beta[1] should be 20 in hex
if alpha is 0x00 00 00 00 00 00 42 AB in hex,
and if i is 1 ,
then beta[2] should be 42 and beta[3] should be AB in hex
Can anyone help me with this?
Assuming alpha is unsigned :
std::vector<std::uint8_t> vec(8);
for(std::size_t j = (i + 1u) * sizeOfAlpha - 1u; sizeOfAlpha; --j, --sizeOfAlpha) {
vec[j] = alpha & 0xff;
alpha >>= 8;
}
Live on Coliru