How to edit nibbles inside a variable? - c++

Suppose I have the following code.
int main(int argc, char *argv[])
{
size_t value = stoul(argv[1], 0, 16);
size_t nibble = stoul(argv[2]);
size_t replacement = stoul(argv[3]) % 16;
cout << hex << value << '\n';
}
I want to write supplementary to this code such that I can type ./a.out value nibble replacement in my terminal, and it will replace whatever digit is in the specified nibble by the replacement. So for example, I would want to type ./a.out 22334 3 11 so that the output I get is 2b334. Nibble here indicates the nibble offset. How would I make my program access the specified nibble?

value &= ~( 0xF << ( nibble * 4 ) );
value |= replacement << ( nibble * 4 );
First we create a mask.
1 1 1 1 0xF
1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0xF << ( nibble * 4 )
1 1 1 1 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 ~( 0xF << ( nibble * 4 ) )
We use this to clear bits from the original value.
0 0 1 0 0 0 1 0 0 0 1 1 0 0 1 1 0 1 0 0 value
& 1 1 1 1 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 mask
-----------------------------------------------
0 0 1 0 0 0 0 0 0 0 1 1 0 0 1 1 0 1 0 0 value & mask
Then we prepare the value to insert.
1 0 1 1 replacement
1 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 replacement << ( nibble * 4 )
Then merge it in.
0 0 1 0 0 0 0 0 0 0 1 1 0 0 1 1 0 1 0 0 value & mask
1 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 replacement << ( nibble * 4 )
| -----------------------------------------------
0 0 1 0 1 0 1 1 0 0 1 1 0 0 1 1 0 1 0 0

You can use the output stream class to work with a string. This makes it much easier to replace any position.
#include <iostream>
#include <sstream>
int main (int argc, char *argv[])
{
std::ostringstream outstream_value;
outstream_value << std::hex << std::stoul(argv[1], 0, 16);
std::string hexstr = outstream_value.str();
const std::size_t length = hexstr.length();
std::ostringstream outstream_replace;
outstream_replace << std::hex << std::stoul(argv[3]) % 16;
const char replace_char = outstream_replace.str()[0];
const std::size_t nibble = std::stoul(argv[2]);
if ( length >= nibble + 1 )
hexstr[length - nibble - 1] = replace_char;
std::cout << hexstr;
return 0;
}

Related

C++ reading from file is not giving expected, or any output

I am trying to make a game which loads it's levels from a text file. I decided to do this with the help of a 2 dimensional vector of integers. Before implementing it in my main code, I first decided to check whether my logic was right so I made a Test.txt file containing the the level I wanted to draw.
Test.txt:-
1 1 0 0 1 0 0 0 0 0 1 1 1 1 1 1 1 0 1 0 1 0 0 1 0 0 1 0 0 1 1 0
1 0 1 0 1 1 1 0 1 1 0 1 1 0 1 1 1 0 1 0 0 1 1 1 1 1 1 0 0 1 0 0
0 0 0 0 0 0 0 1 0 1 0 0 0 1 1 0 1 1 0 0 0 0 0 0 1 0 0 1 0 1 1 0
0 0 1 1 1 1 1 0 0 0 1 0 1 0 1 1 0 0 0 1 1 1 1 0 0 0 1 0 1 1 1 0
1 0 0 0 1 0 0 0 1 1 1 1 1 1 1 1 1 1 1 0 1 0 0 0 0 0 1 0 0 1 0 1
0 1 0 1 0 1 1 1 0 0 1 0 0 0 0 1 0 1 0 0 1 0 1 1 0 0 0 0 1 1 0 1
0 1 1 1 0 1 1 0 1 0 1 1 0 1 1 0 0 1 0 0 0 1 1 0 1 1 1 1 1 1 0 1
0 0 0 0 0 0 0 1 1 0 1 1 0 0 0 0 0 1 0 1 0 1 1 0 0 1 0 0 0 1 0 0
0 0 1 1 1 0 0 0 1 0 0 1 1 1 1 0 0 1 1 0 0 0 1 1 1 0 1 1 1 1 0 1
0 1 0 0 1 1 0 0 1 0 1 1 0 1 0 0 1 1 0 1 1 0 1 0 0 1 1 1 1 0 1 1
1 1 0 1 1 1 1 0 0 1 0 0 1 0 0 1 0 1 0 1 1 1 1 1 0 0 0 1 1 0 1 0
0 0 1 0 0 0 1 1 1 0 1 0 0 1 0 1 1 0 0 0 1 1 0 1 0 0 0 0 1 1 0 1
0 1 1 0 0 0 0 0 0 1 1 0 1 1 0 1 1 0 1 0 0 1 0 0 1 1 0 1 1 1 1 0
1 0 1 1 1 0 1 1 1 1 0 0 0 0 0 0 1 0 1 0 0 0 1 1 1 0 0 1 1 0 0 0
1 0 1 1 0 0 0 0 1 0 0 1 1 0 0 0 1 0 0 1 0 0 0 1 0 1 0 1 1 0 0 1
0 0 1 1 1 0 1 1 1 0 1 0 0 0 1 0 1 1 1 1 0 0 0 0 0 0 1 1 1 1 1 0
0 0 0 1 0 1 0 1 0 1 0 0 1 1 1 0 0 1 1 0 1 0 1 0 1 1 1 0 0 0 1 0
1 0 1 0 1 0 0 0 1 1 0 0 0 1 0 1 1 1 1 1 0 0 1 0 1 0 1 1 1 1 1 1
Each integer is seperated by a space and only one number is supposed to be read once at a time. The 1 and 0 tell the game which tile to draw. Now, with this wrote the following code in c++ to read the file and populate the vector with it's contents. After that it's supposed to output the contents of the vector.
Test.cpp:-
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int num;
vector<vector<int>> nums;
int main(void) {
ifstream FileIn;
FileIn.open("Test.txt");
for(int i = 0; i < 18; i++) {
vector<int> temp;
for(int j = 0; j < 32; j++) {
FileIn >> num;
temp.push_back(num);
}
nums.push_back(temp);
temp.clear();
}
cout << nums.size() << '\n'; // outputs 18
for (unsigned int i=0; i < nums.size(); i++) {
for (unsigned int j=0; j < nums[i].size(); j++) {
cout << nums[i][j];
if (j == nums[i].size() - 1) cout << '\n';
}
}
FileIn.close();
return 0;
}
but this is where the problem starts. The code doesn't output anything to the terminal it just starts and then goes back to the prompt.
The executable compiles with no errors and there are no crashes or runtime error either. There is just no output.
Things i have tried:
Putting in spaces between the numbers
Keeping all integers on the same line
both of the solutions above, but together this time
I am using atom with the platformio terminal plugin on windows 10 (64-bit) on a intel with amd-64 architecture. Any help would be very appreciated.
A few things: Start learning how to use a debugger. Your question to stackoverflow is something you probably could easily answer on your own, if you stepped through your code with a debugger. That'd save you time - and us.
Edited:
Also, you open 'test.txt' without verifying or setting the "current working directory". This will work only if you start the application from the same path, test.txt is in. But if you run the app from someplace else, the working directory may be different.
You did not check for eof or any other error condition. How do you know if opening the file did actually work? Or reading the number? Or that there are exactly the amount of numbers you are expecting.
Checking error conditions may seem like a nuisance, but it's definitely not. Hunting for errors, which you did not check in your code, is much more time consuming than forming a habit to check for errors.
Here is some code:
ifstream FileIn;
FileIn.open("test.txt");
if (!FileIn.good())
cerr << "Could not open file...";
else {
while (!FileIn.eof()) {
int num; ///!!! DONT make `num` a global variable
FileIn >> num;
if (FileIn.bad()) {
cerr << "Invalid number in file...";
return 1; // return prematurely from the application
}
// Do something with the number
}
}
Also, use cout << endl instead of cout << '\n';. endl is the official way of inserting a line break and it will work on any platform, whereas '\n' may or may not work. Some platforms require two characters.
So I finally found the problem, the code, logic, text file everything were working fine. After taking the advice about debuggers from the other answer, this time instead of using atom's terminal plugin, I used powershell and it worked. It gave the output i was expecting. Then i tried the same code with the atom's terminal and that gave no output. So the problem seemed to be not in the code but in the terminal I was using.

Inverting bits of PBM image while vs for loop

I am trying to flip the color of pixels of a simple pbm image which has only pure black and pure white. I am generating the image myself and then reading it and then flipping the bits and saving both the generated image and the color inverted image.
Here is my code (write_pbm.cpp) -
#include "headers/write_pbm.h"
int width_pbm, height_pbm;
void input_sample_dim(){
printf("Enter the width and height of image to create = ");
scanf("%d %d", &width_pbm, &height_pbm);
}
void create_sample_image(){
FILE *fp;
fp = fopen("sample.pbm", "wb");
fprintf(fp, "P1\n");
fprintf(fp, "# myfile.pbm\n");
fprintf(fp, "%d %d\n", width_pbm, height_pbm);
for (int i = 1; i <= height_pbm; i++)
{
for (int j = 1; j <= width_pbm; j++)
{
if (j == i || (width_pbm - j + 1 == i))
fprintf(fp, "0");
else
fprintf(fp, "1");
if (j == width_pbm)
fprintf(fp, "\n");
else
fprintf(fp, " ");
}
}
fclose(fp);
}
void invert (){
printf("\tinverting the image\nturning black pixels white and white pixels black\n");
FILE *fp = fopen("sample.pbm", "rb");
while(fgetc(fp) != '\n');
while(fgetc(fp) != '\n');
while(fgetc(fp) != '\n');
FILE *fp_inv;
fp_inv = fopen("inverted.pbm", "wb");
fprintf(fp_inv, "P1\n");
fprintf(fp_inv, "# inverted.pbm\n");
fprintf(fp_inv, "%d %d\n", width_pbm, height_pbm);
for (int i = 1; i <= height_pbm; i++){
for (int j = 1; j <= width_pbm; j++){
char ch = fgetc(fp);
if (ch == '1')
fputc('0', fp_inv);
else if (ch == '0')
fputc('1', fp_inv);
else
fputc(ch, fp_inv);
}}
fclose(fp);
fclose(fp_inv);
}
Below is the header I am including (write_pbm.h)
#ifndef Write_PBM_H
#define Write_PBM_H
#include <cstdio>
#include <iostream>
void create_sample_image(void);
void input_sample_dim(void);
void invert (void);
extern int width_pbm, height_pbm;
#endif
Below is my main -
#include "write/PBM/headers/write_pbm.h"
int main(){
input_sample_dim();
printf("writing sample image\n");
create_sample_image();
printf("sample image with dimenstions %d by %d created\n", width_pbm, height_pbm);
invert();
}
So I am making a V cross kind of pattern and then inverting the colors and saving both of the created image and the inverted image.
Lets suppose we provide input 10 10
then the file sample.pbm looks like
P1
# myfile.pbm
10 10
0 1 1 1 1 1 1 1 1 0
1 0 1 1 1 1 1 1 0 1
1 1 0 1 1 1 1 0 1 1
1 1 1 0 1 1 0 1 1 1
1 1 1 1 0 0 1 1 1 1
1 1 1 1 0 0 1 1 1 1
1 1 1 0 1 1 0 1 1 1
1 1 0 1 1 1 1 0 1 1
1 0 1 1 1 1 1 1 0 1
0 1 1 1 1 1 1 1 1 0
and inverted.pbm looks like this
P1
# inverted.pbm
10 10
1 0 0 0 0 0 0 0 0 1
0 1 0 0 0 0 0 0 1 0
0 0 1 0 0 0 0 1 0 0
0 0 0 1 0 0 1 0 0 0
0 0 0 0 1 1 0 0 0 0
as you can see that only half the rows are getting printed in the inverted image.
If I replace the nested loops of invert() of write_pbm.cpp with
char ch;
while(!feof(fp))
{
char ch = fgetc(fp);
if (ch == '1')
fputc('0', fp_inv);
else if (ch == '0')
fputc('1', fp_inv);
else
fputc(ch, fp_inv);
}
then it gives the right output in the inverted.pbm file which is
P1
# inverted.pbm
10 10
1 0 0 0 0 0 0 0 0 1
0 1 0 0 0 0 0 0 1 0
0 0 1 0 0 0 0 1 0 0
0 0 0 1 0 0 1 0 0 0
0 0 0 0 1 1 0 0 0 0
0 0 0 0 1 1 0 0 0 0
0 0 0 1 0 0 1 0 0 0
0 0 1 0 0 0 0 1 0 0
0 1 0 0 0 0 0 0 1 0
1 0 0 0 0 0 0 0 0 1
\FF
I am doing the same thing through both the nested loops and the while loop then why is it giving the wrong output in case of nested for loops?
Thanks for reading this, Please provide your valuable response.
Looking at your input file, it appears that every meaningful char (i.e. '0' or '1') is followed by a space.
In the while loop that is working, you read as many chars as needed, until the end of file, just inverting the correct chars and copying unexpected chars. So everything is processed.
In the nested for loops, you are reading the exact number of chars corresponding to the dimensions of the picture so 10*10. Taking into account the layout of the input file, you are therefore reading only 100 chars, so 50 '1' or '0' and 50 spaces. So you process only half of the input.
Unrelated: your code uses C++ header, but all the rest is just plain C. In C++, you should consider to use fstream to read your files, and not the C legacy FILE* API.

Writing a 2D vector to a file? c++

I'm wondering how I can output a 2D vector to a file with spaces in between the values. It's to write a map to a file at a specified size that the user chooses. I am already dynamically loading the map from there. I have a basis for the function but I'm kind of lost on the next bit.
void Map::SetMapSize(int sizeX, int sizeY, const char *filename)
{
std::ofstream out(filename);
out << "[Map]" << std::endl;
MapSizeVector[sizeX][sizeY];
for(int i = 0; i <= sizeX; i++)
{
for(int j = 0; j <= sizeY; j++)
{
std::ostream_iterator<std::string> output_iterator(out, " ");
}
}
}
The Map.txt looks like this:
[Map]
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 1 1 0 0 0 1 1 0 0 1 1 1 1 1 1 0 0
0 0 1 1 0 0 0 1 1 0 0 1 1 1 1 1 1 0 0
0 0 1 1 0 0 0 1 1 0 0 0 0 1 1 0 0 0 0
0 0 1 1 0 0 0 1 1 0 0 0 0 1 1 0 0 0 0
0 0 1 1 1 1 1 1 1 0 0 0 0 1 1 0 0 0 0
0 0 1 1 1 1 1 1 1 0 0 0 0 1 1 0 0 0 0
0 0 1 1 0 0 0 1 1 0 0 0 0 1 1 0 0 0 0
0 0 1 1 0 0 0 1 1 0 0 0 0 1 1 0 0 0 0
0 0 1 1 0 0 0 1 1 0 0 1 1 1 1 1 1 0 0
0 0 1 1 0 0 0 1 1 0 0 1 1 1 1 1 1 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
It also has a details bit underneath it. Basically, I want to rewrite that [Map] part to whatever size x and y the user requests above the [Details] and replacing the existing [Map] part. The numbers are fine with being 0. Thanks!
Declaration of vector in Map.h
std::vector <std::vector <int> > MapSizeVector;
Your function should look like this:
void Map::SetMapSize(int sizeX, int sizeY, const char *filename)
{
std::ofstream out(filename);
out << "[Map]" << std::endl;
MapSizeVector.resize(sizeX);
for(int i = 0; i < sizeX; i++)
{
MapSizeVector[i].resize(sizeY);
for(int j = 0; j < sizeY; j++)
{
char str[20];
sprintf(str, "%d ", MapSizeVector[i][j]);
out << str;
}
out << '\n';
}
}

C++ map matrix column into rank - bit manipulations

I've got (binary) matrices represented by uint64_t (from C++11). And I'd like to be able to efficiently map from any column into first rank. For example
0 1 0 0 0 0 0 0
0 1 0 0 0 0 0 0
0 1 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0
0 1 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0
uint64_t matrice = 0x4040400040400040uLL;
uint64_t matrice_2 = map(matrice, ColumnEnum::Column2);
1 1 1 0 1 1 0 1
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
matrice_2 contains 0xED00000000000000uLL;
Great question. I really enjoyed the hacking. Here is my solution:
uint64_t map(uint64_t x, int column)
{
x = (x >> (7 - column)) & 0x0101010101010101uLL;
x = (x | (x >> 7)) & 0x00FF00FF00FF00FFuLL;
x = (x | (x >> 14))& 0x000000FF000000FFuLL;
x = (x | (x >> 28))& 0x00000000000000FFuLL;
return x << 56;
}
A working example can be found at ideone, where the call is really map(matrice, ColumnEnum::Column2).
A nice little riddle. Here is a reasonably readable version:
matrice = (matrice >> (8ull - column)) & 0x0101010101010101ull;
uint64_t result(( ((matrice >> 0ul) & 0x01ull)
| ((matrice >> 7ul) & 0x02ull)
| ((matrice >> 14ull) & 0x04ull)
| ((matrice >> 21ull) & 0x08ull)
| ((matrice >> 28ull) & 0x10ull)
| ((matrice >> 35ull) & 0x20ull)
| ((matrice >> 42ull) & 0x40ull)
| ((matrice >> 49ull) & 0x80ull)) << 56ull);
First define bitmask for every column:
uint64_t columns[8] = {
0x8080808080808080uLL,
0x4040404040404040uLL,
//...
0x0101010101010101uLL
};
by applying column bitmask to your "matrice" you get only this column:
uint64_t col1 = matrice & columns[1]; // second column - rest is empty
by shifting you can get only first column case:
uint64_t col0 = (col1 << 1); // second column - rest is empty
// ^ this number is just zero based index of column,,,
Now first bit is on right place - just set the next 7 bits:
col0 |= (col0 & (1 << 55)) << 7; // second bit...
// ....
Or just use std::bitset<64>, I would do....

Exact Large Finite Field Linear Algebra Library (e.g. GF(2^128) / GF(2^256) ) [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking us to recommend or find a book, tool, software library, tutorial or other off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 8 years ago.
Improve this question
General
I'm looking for a library that is able to do exact calculations on large finite fields such as GF(2128)/𝔽2128 and GF(2256)/𝔽2256. I listed the features that I need and the features that would be cool below. Obviously, the library should be as fast as possible :-). Ah, since I'm no C++ master (and probably most of the libraries are C++), sample code of say generate a random element/a constant and multiply it to it's multiplicative inverse
Must-Have Features
Addition of field elements
Multiplication of field element
Find the multiplicative inverse of a field element
Nice to Have Features
Vector/Matrix support
Random Element support
Libraries I already looked at that will probably not work
FFLAS/FFPACK, seems not to work with such large finite fields
Givaro, seems not to work on such large finite fields
Libraries I already looked at that could work (but I was unable to use)
NTL, I was not able to invert an element, but it should really work since SAGE seems to use this library when defining GF(2^256) and there an element can be inverted using x^(-1)
PARI/GP, I was not able to find everything I need in the documentation, but the SAGE documentation kind of says that it should work
Other notes
I'm writing a Haskell program and will interface that library later, so easier Haskell interfacing is better :-)
The NTL library seems to work, using this (sorry I'm quite unable to program in C++) code
#include <NTL/GF2E.h>
#include <NTL/GF2EX.h>
#include <NTL/GF2X.h>
#include <NTL/GF2XFactoring.h>
NTL_CLIENT
int main()
{
GF2X P = BuildIrred_GF2X(256);
GF2E::init(P);
GF2E zero = GF2E::zero();
GF2E one;
GF2E r = random_GF2E();
GF2E r2 = random_GF2E();
conv(one, 1L);
cout << "Cardinality: " << GF2E::cardinality() << endl;
cout << "ZERO: " << zero << " --> " << IsZero(zero) << endl;
cout << "ONE: " << one << " --> " << IsOne(one) << endl;
cout << "1/r: " << 1/r << ", r * (1/r): " << (r * (1/r)) << endl;
cout << "1/r2: " << 1/r2 << ", r2 * (1/r2): " << (r2 * (1/r2)) << endl;
}
it seems to work, proof (output of this program):
Cardinality: 115792089237316195423570985008687907853269984665640564039457584007913129639936
ZERO: [] --> 1
ONE: [1] --> 1
1/r: [0 1 0 1 1 0 1 1 1 0 1 1 1 0 0 1 1 0 1 1 1 0 1 1 0 0 0 0 0 1 0 1 0 1 1 0 1 1 0 0 0 0 0 0 1 1 1 0 1 1 1 0 1 0 1 0 0 0 1 1 1 0 1 1 1 1 0 1 0 1 0 1 1 0 1 1 1 0 0 0 1 0 0 1 0 1 1 1 0 1 1 0 1 1 0 0 0 0 0 1 1 0 1 0 1 0 0 0 0 0 1 0 0 1 1 0 0 1 0 0 1 0 1 1 1 1 0 0 1 1 0 1 0 1 1 1 1 1 1 0 1 1 0 0 0 0 0 1 1 0 1 0 0 1 1 1 0 1 1 1 1 1 0 1 0 1 0 0 0 1 1 0 0 1 1 0 0 1 0 1 1 1 0 1 1 1 1 1 0 1 1 0 1 1 1 1 0 1 0 0 0 0 1 1 1 0 1 1 1 0 1 1 1 1 1 1 1 1 0 1 0 1 0 0 1 1 0 1 1 0 1 1 1 1 1 0 0 1 1 0 1 0 1 0 0 0 0 1 1 0 0 1 1 1 0 1], r * (1/r): [1]
1/r2: [1 0 1 1 0 0 0 0 1 0 1 0 0 0 1 0 0 0 1 1 0 0 1 0 1 0 0 0 1 1 1 0 0 0 1 1 1 1 1 0 1 0 1 1 0 0 1 1 1 0 1 0 1 0 0 1 0 0 0 0 1 1 1 0 0 0 1 1 1 1 1 0 0 1 0 0 0 1 1 0 1 0 1 1 1 0 0 1 0 1 0 1 0 0 1 0 0 0 1 0 0 1 1 1 1 1 0 0 0 0 1 1 1 0 1 0 1 0 1 0 0 0 1 0 1 0 1 1 0 0 0 1 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 1 1 1 0 1 1 0 0 0 0 1 1 0 1 1 1 0 1 0 0 0 0 0 1 1 0 1 1 1 0 0 0 0 1 1 0 1 0 0 0 0 1 0 0 0 0 1 1 1 1 1 0 1 0 1 1 0 1 0 1 0 1 1 1 1 0 0 1 1 0 1 1 1 1 1 0 1 1 1 0 1 0 0 0 0 1 0 1 1 0 0 0 1 1 0 0 1 1 0 1 0 0 1 0 1 0 0 1 1], r2 * (1/r2): [1]
Even inverting seems to work (scroll as right as possible in the output sample above) :-)