Convert Binary to int without Convert.ToInt32 - .net-micro-framework

I need to convert binary 10100101 to an integer in C# without using Convert.ToInt64(bin,2), I'm working with the .net micro framework. When I use int i = Convert.ToInt32(byt, 2); an exception is thrown with the rather unhelpfull message of:
#### Exception System.ArgumentException - 0x00000000 (1) ####
#### Message:
#### System.Convert::ToInt32 [IP: 000d] ####
#### TRNG.Program::loop [IP: 0047] ####
#### TRNG.Program::Main [IP: 0011] ####
A first chance exception of type 'System.ArgumentException' occurred in mscorlib.dll
An unhandled exception of type 'System.ArgumentException' occurred in mscorlib.dll

Slightly faster than Femaref's option, as it doesn't require a pesky method call, and uses OR instead of ADD just for fun:
public static int ParseBinary(string input)
{
// Count up instead of down - it doesn't matter which way you do it
int output = 0;
for (int i = 0; i < input.Length; i++)
{
if (input[i] == '1')
{
output |= 1 << (input.Length - i - 1);
}
}
return output;
}
You may want to:
Check that the length is less than 32 to start with
Check that every character is '0' or '1'
Just for LOLs, here's a LINQ version:
public static int ParseBinary(string input)
{
return input.Select((c, index) => new { c, index })
.Aggregate(0, (current, z) => current | (z.c - '0') <<
(input.Length - z.index - 1));
}
Or neater yet:
public static int ParseBinary(string input)
{
return return input.Aggregate(0, (current, c) => (current << 1) | (c - '0'));
}

string input = "10101001";
int output = 0;
for(int i = 7; i >= 0; i--)
{
if(input[7-i] == '1')
output += Math.Pow(2, i);
}
in general:
string input = "10101001";
int output = 0;
for(int i = (input.Length - 1); i >= 0; i--)
{
if(input[input.Length - i] == '1')
output += Math.Pow(2, i);
}

Related

How to implement ThreadPool::RunAsync in Winrt/C++

I am trying to understand how I could implement a concurrent thread for processing data in a Winrt/Cpp application.
As background
I have implemented a winRT BLE component that wraps the windows bluetooth function
I am using this component in my winrt application and successfully get a notification when the app connects to me bluetooth device
Now within the app I would like to "spawn" a process that continually sends a request to the BLE device and process the response.
To achieve #3 I thought one approach could be - within the connection notification I would invoke a function called StartDataAcq that uses the threadpool to schedule work,
to test out this approach I decided to just use the example shown here
https://learn.microsoft.com/en-us/windows/uwp/threading-async/submit-a-work-item-to-the-thread-pool
to see if it could work
So the implementation looks like this within my code
void Datamanager::BleFound(
winrt::Windows::Foundation::IInspectable const& /* sender */,
uint32_t foundFlags)
{
OutputDebugStringW((L"Member function Called from DataManager->" + hstring(std::to_wstring(foundFlags)) + L"\r\n").c_str());
if (!acqStarted)
{
StartDataAcq();
acqStarted = true;
}
}
void DataManager::StartDataAcq()
{
// The nth prime number to find.
const unsigned int n{ 99999999 };
unsigned long nthPrime{ 0 };
//submit work to thread poool
m_workItem = Windows::System::Threading::ThreadPool::RunAsync([&](Windows::Foundation::IAsyncAction const& workItem)
{
unsigned int progress = 0; // For progress reporting.
unsigned int primes = 0; // Number of primes found so far.
unsigned long int i = 2; // Number iterator.
if ((n >= 0) && (n <= 2))
{
nthPrime = n;
return;
}
while (primes < (n - 1))
{
if (workItem.Status() == Windows::Foundation::AsyncStatus::Canceled)
{
break;
}
// Go to the next number.
i++;
// Check for prime.
bool prime = true;
for (unsigned int j = 2; j < i; ++j)
{
if ((i % j) == 0)
{
prime = false;
break;
}
};
if (prime)
{
// Found another prime number.
primes++;
// Report progress at every 10 percent.
unsigned int temp = progress;
progress = static_cast<unsigned int>(10.f * primes / n);
if (progress != temp)
{
std::wstringstream updateString;
updateString << L"Progress to " << n << L"th prime: " << (10 * progress) << std::endl;
OutputDebugStringW((L"" + updateString.str() + L"\r\n").c_str());
// Update the UI thread with the CoreDispatcher.
/*
Windows::ApplicationModel::Core::CoreApplication::MainView().CoreWindow().Dispatcher().RunAsync(
Windows::UI::Core::CoreDispatcherPriority::High,
Windows::UI::Core::DispatchedHandler([&]()
{
UpdateUI(updateString.str());
}));
*/
}
}
}
// Return the nth prime number.
nthPrime = i;
} , Windows::System::Threading::WorkItemPriority::Normal, Windows::System::Threading::WorkItemOptions::TimeSliced);
}
I see the message for the connect notification,
This debug string - OutputDebugStringW((L"Member function Called from DataManager->" + hstring(std::to_wstring(foundFlags)) + L"\r\n").c_str());
however I never see any output from the async workitem.
Can someone please help me spot the issue?
Also are there any better ways to do this? I was reading about co-routines but seeing how the work is data processing locally I do not think a co routine would work
I also was trying to find out how I could spawn a separate thread and manage it within my code - but am not sure how to do it within the winrt/c++ framework
based on Raymond Chen's comment I converted the variables on the stack to std::shared_ptr and the sample works now...
Also stumbled upon this link that explains this better than I can...
https://learn.microsoft.com/en-us/cpp/parallel/concrt/task-parallelism-concurrency-runtime?view=msvc-170#lambdas
void DataManager::StartDataAcq()
{
auto n = make_shared<UINT32>(9999);
auto nthPrime = make_shared<UINT32>(0);
m_workItem = Windows::System::Threading::ThreadPool::RunAsync([n,nthPrime](Windows::Foundation::IAsyncAction const& workItem)
{
unsigned int progress = 0; // For progress reporting.
unsigned int primes = 0; // Number of primes found so far.
int i = 2; // Number iterator.
if ((*n >= 0) && (*n <= 2))
{
*nthPrime = *n;
//return;
}
while (primes < (*n - 1))
{
if (workItem.Status() == Windows::Foundation::AsyncStatus::Canceled)
{
break;
}
// Go to the next number.
i++;
// Check for prime.
bool prime = true;
for (unsigned int j = 2; j < i; ++j)
{
if ((i % j) == 0)
{
prime = false;
break;
}
};
if (prime)
{
// Found another prime number.
primes++;
// Report progress at every 10 percent.
unsigned int temp = progress;
progress = static_cast<unsigned int>(10.f * primes / *n);
if (progress != temp)
{
std::wstringstream updateString;
updateString << L"Progress to " << *n << L" " << i << L" th prime: " << (10 * progress) << std::endl;
OutputDebugStringW((L"" + updateString.str() + L"\r\n").c_str());
// Update the UI thread with the CoreDispatcher.
/*
Windows::ApplicationModel::Core::CoreApplication::MainView().CoreWindow().Dispatcher().RunAsync(
Windows::UI::Core::CoreDispatcherPriority::High,
Windows::UI::Core::DispatchedHandler([&]()
{
UpdateUI(updateString.str());
}));
*/
}
}
}
// Return the nth prime number.
*nthPrime = i;
std::wstringstream updateString;
updateString << L"Found the nth prime " << i << std::endl;
OutputDebugStringW((L"" + updateString.str() ).c_str());
} , Windows::System::Threading::WorkItemPriority::Normal, Windows::System::Threading::WorkItemOptions::TimeSliced);
}

calculator using ioctl of linux device driver

I am learning linux device drivers
So i am trying to write a code for calculator where user will give input using userspace program but the calculations will happen in kernel
I am using ioctl to pass values to kernel
It works fine first time(i.e. after inserting the device driver) ,but after that it gives incorrect output. So if i again want correct answer i do rmmod driver and again insmod driver
Whats wrong with the code ?
Is there any better way to map operation ,value1 and value2 than using the count variable as i am using in driver code
following is the output
where first time i get the correct output,but the second time a garbage value:
calculator_ioctl$ ./a.out
*************************************
Opening Driver
Operation to perform
1. Add
2. Subtract
3. Multiply
4. Divide
2
Enter first value :45
Enter second value :11
writing value to driver
Reading value from driver
value is 34
closing driver
calculator_ioctl$ ./a.out
*************************************
Opening Driver
Operation to perform
1. Add
2. Subtract
3. Multiply
4. Divide
2
Enter first value :45
Enter second value :11
writing value to driver
Reading value from driver
value is -1410510832
closing driver
driver code:
#include<linux/kernel.h>
#include<linux/init.h>
#include<linux/module.h>
#include<linux/kdev_t.h>
#include<linux/fs.h>
#include<linux/cdev.h>
#include<linux/device.h>
#include<linux/slab.h> //kmalloc.h
#include<linux/uaccess.h> //copy to/from user
#include<linux/ioctl.h>
#define WR_VALUE _IOW('a','a',int32_t*)
#define RD_VALUE _IOR('a','b',int32_t*)
int32_t value1 = 0 ;
int32_t value2 = 0 ;
int32_t value = 0 ;
int32_t oper = 0 ;
dev_t dev=0;
static struct class *dev_class;
static struct cdev etx_cdev ;
static int __init etx_driver_init(void);
static void __exit etx_driver_exit(void);
static long etx_ioctl(struct file *file,unsigned int cmd,unsigned long arg);
static struct file_operations fops =
{
.owner = THIS_MODULE,
.unlocked_ioctl = etx_ioctl,
};
static long etx_ioctl(struct file *file,unsigned int cmd,unsigned long arg)
{
static int count = 0;
switch(cmd) {
case WR_VALUE:
if(count == 0)
{
copy_from_user(&oper,(int32_t*)arg,sizeof(oper));
printk(KERN_INFO "oper = %d\n",oper);
break;
}
else if(count == 1){
copy_from_user(&value1,(int32_t*)arg,sizeof(value1));
printk(KERN_INFO "value1 = %d\n",value1);
break;
}
else if(count == 2){
copy_from_user(&value2,(int32_t*)arg,sizeof(value2));
printk(KERN_INFO "value2 = %d\n",value2);
break;
}
case RD_VALUE:
if(oper == 1)
value = value1 + value2 ;
else if(oper == 2)
value = value1 - value2;
else if(oper == 3)
value = value1 * value2;
else if(oper == 4)
value = value1 / value2;
else
break;
copy_to_user((int32_t*) arg, &value,sizeof(value));
break;
}
count+=1 ;
if(count == 3)
count = 0 ;
return 0;
}
static int __init etx_driver_init(void)
{
if((alloc_chrdev_region(&dev,0,1,"etx_dev")) <0){
printk(KERN_INFO"cannot allocate major number\n");
return -1;
}
printk(KERN_INFO " MAJOR = %d Minor = %d\n",MAJOR(dev),MINOR(dev));
cdev_init(&etx_cdev,&fops);
if((cdev_add(&etx_cdev,dev,1)) < 0){
printk(KERN_INFO "cannot add device to the system\n");
goto r_class;
}
/*Creating struct class*/
if((dev_class = class_create(THIS_MODULE,"etx_class")) == NULL){
printk(KERN_INFO "Cannot create the struct class\n");
goto r_class;
}
/*Creating device*/
if((device_create(dev_class,NULL,dev,NULL,"etx_device")) == NULL){
printk(KERN_INFO "Cannot create the Device 1\n");
goto r_device;
}
printk(KERN_INFO "Device Driver Insert...Done!!!\n");
return 0;
r_device:
class_destroy(dev_class);
r_class:
unregister_chrdev_region(dev,1);
return -1;
}
void __exit etx_driver_exit(void)
{
device_destroy(dev_class,dev);
class_destroy(dev_class);
cdev_del(&etx_cdev);
unregister_chrdev_region(dev, 1);
printk(KERN_INFO "Device Driver Remove...Done!!!\n");
}
module_init(etx_driver_init);
module_exit(etx_driver_exit);
MODULE_LICENSE("GPL");
application:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<sys/ioctl.h>
#define WR_VALUE _IOW('a','a',int32_t*)
#define RD_VALUE _IOR('a','b',int32_t*)
int main()
{ int num;
int fd;
int32_t value,number1,number2,output,operation;
printf("\n*************************************\n");
printf("\nOpening Driver\n");
fd = open("/dev/etx_device",O_RDWR);
if(fd<0) {
printf("Cannot open device file ...\n");
return 0;
}
printf("Operation to perform\n\n");
printf("\
1. Add \n \
2. Subtract \n \
3. Multiply \n \
4. Divide \n\n\n ");
scanf("%d",&num);
if(num > 4 && num < 1)
{
printf("Enter between 1 and 4");
return 0;
}
ioctl(fd,WR_VALUE,(int32_t*) &num);
printf("Enter first value :");
scanf("%d",&number1);
printf("Enter second value :");
scanf("%d",&number2);
printf("writing value to driver\n");
ioctl(fd,WR_VALUE,(int32_t*) &number1);
ioctl(fd,WR_VALUE,(int32_t*) &number2);
printf("Reading value from driver \n");
ioctl(fd,RD_VALUE,(int32_t*)&value);
printf("value is %d\n",value);
printf("closing driver\n");
close(fd);
}

C++ std::map set and get using operator[]

I'm trying to build a 2D sparse matrix class using std::map, which should be called in (for example) the following way:
SparseMatrix<double> M(2,2); // Create a new sparse matrix with 2 rows and 2 columns
M[{1,1}] = 3.1; // Sets element {1,1} to 3.1
The following class can perform these tasks:
template < typename T >
class SparseMatrix
{
std::map< array<int, 2>, T> data;
const array<int, 2> size;
public:
SparseMatrix(const int rows, const int cols)
: size({ rows, cols }) {}
// []-operator to set and get values from matrix
T& operator[](const array< int,2 > indices)
{
// Check if given indices are within the size of the matrix
if(indices[0] >= size[0] || indices[1] >= size[1])
throw invalid_argument("Indices out of bounds");
return data[indices];
}
};
Using this class it is possible to create a new object and set the element, however, the []-operator is also used to get elements, for example:
std::cout << M[{1,1}] << std::endl;
The problem with this is that if this is used to get an element that is not set already, it creates a new part in the map with the given indices and a value of 0, which is undesired for a sparse matrix class, as the map should only contain the non-zero elements.
Is it possible to solve this problem with the []-operator by making a distinction between 'setting' and 'getting'? In case of 'getting' should the operator only return a 0 without adding it to the map.
You can differentiate between reading and writing by using a proxy instead of a T&. Only showing the relevant code:
template <typename T>
class SparseMatrixProxy {
public:
//for reading an element:
operator T() const {
// Check if given indices are within the size of the matrix
if (indices[0] >= matrix.size[0] || indices[1] >= matrix.size[1])
throw std::invalid_argument("Indices out of bounds");
auto map_it = matrix.data.find(indices);
if (map_it == matrix.data.end()) {
return T{};
}
return map_it->second;
}
//for writing an element:
auto operator=(const T &t) {
//optional: when setting a value to 0 erase it from the map
if (t == T{}) {
matrix.data.erase(indices);
} else {
matrix.data[indices] = t;
}
return *this;
}
};
to be used in SparseMatrix like this:
// []-operator to set and get values from matrix
SparseMatrixProxy<T> operator[](const std::array<int, 2> indices) {
return {*this, indices};
}
With usage:
SparseMatrix<double> M(2, 2); // Create a new sparse matrix with 2 rows and 2 columns
M[{{1, 1}}] = 3.1; // Sets element {1,1} to 3.1
std::cout << M[{{1, 1}}] << '\n';
assert(M.mapsize() == 1); //1 element for index {1,1}
std::cout << M[{{0, 0}}] << '\n';
assert(M.mapsize() == 1); //still 1 element because reading doesn't insert an element
M[{{1, 1}}] = 0;
assert(M.mapsize() == 0); //0 elements because we set the only non-0 element to 0
Complete example.
There is std::map::find method. It returns an iterator and if it equals to map.end() then it means that the element is absent in the map.
Yup, it's a pain in the backside. Luckily the clever C++11 bods realised this and gave us a new method: at.
Use the at method (available from the C++11 standard onwards), which does not do any insertion, although you still need a catch handler for a possible std::out_of_range exception.
See http://en.cppreference.com/w/cpp/container/map/at
It's cheaper from performance point of view to implement sparse matrix by creating own mapping, e.g via storing indices.
template<typename T>
class SparseMatrix
{
...
int m, n;
vector<T> values;
vector<int> cols;
vector<int> rows;
}
template<typename T>
T SparseMatrix<T>::get(int row, int col) const
{
this->validateCoordinates(row, col);
int currCol = 0;
for (int pos = rows.at(row - 1) - 1; pos < rows.at(row) - 1; pos++)
{
currCol = cols.at(pos);
if (currCol == col)
return vals.at(pos);
else if (currCol > col)
break;
}
return T();
}
template<typename T>
SparseMatrix<T> & SparseMatrix<T>::set(T val, int row, int col)
{
// Validate coordinates here?
int pos = rows.at(row - 1) - 1;
int currCol = 0;
for (; pos < rows.at(row) - 1; pos++) {
currCol = cols.at(pos);
if (currCol >= col) {
break;
}
}
if (currCol != col) {
if (!(val == T())) {
this->insert(pos, row, col, val);
}
} else if (val == T()) {
this->remove(pos, row);
} else {
vals.at(pos) = val;
}
return *this;
}
template<typename T>
void SparseMatrix<T>::insert(int index, int row, int col, T val)
{
vals.insert(vals.begin() + index, val);
cols.insert(cols.begin() + index, col);
for (int i = row; i <= this->m; i++)
rows.at(i) = rows.at(i) + 1;
}
And so on...

issue in my if statement to make comparison in my java program

any help please, so i already wrote the prog but my if statement in my for loop is not working. the prog need to generate 6 random nos,then apply bubble sort which i already did.then the user must enter 6 numbers and these numbers must be compared against the random numbers and must say whether numbers are found in the random numbers or not. here's the code. something is wrong with the if statement ` public static void main(String[] args) {
try {
int numbers[] = new int[6]; //random numbers will be stored in new array
//2 loop will be created to avoid duplication of numbers
System.out.println("Array before Bubble sort");
for (int i = 0; i < 6; i++) {
numbers[i] = (int) (Math.random() * 40);
if (i > 0) {
for (int b = 0; b < i; b++) { //
if (numbers[b] == numbers[i]) {
i--; //decrement to continue the for loop if the integer has been repeated
}
}
}
System.out.print(numbers[i] + ","); //random numbers will be printed before using sorting bubble sort
}
//sort an array using bubble sort
bubbleSort(numbers);
System.out.println(" \nArray after bubble sort");
for (int i = 0; i < 6; i++) {
System.out.print(numbers[i] + ",");
}
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
System.out.println("\ninput 6 number between 1 and 40");
int inputNumber = Integer.parseInt(input.readLine());
for (int b = 0; b < 6; b++) {
System.out.println("number:");
int outcome=Integer.parseInt(input.readLine());
if(outcome==numbers){
System.out.println("found in random numbers");
}else{
System.out.println("not found in random numbers");
}
}
} catch (Exception e) {
System.out.println("error");
}
}
public static void bubbleSort(int[] numbers) {
int n = numbers.length;
int temp = 0;
for (int i = 0; i < n; i++) {
for (int j = 1; j < (n - i); j++) {
if (numbers[j - 1] > numbers[j]) { //swap the element
temp = numbers[j - 1];
numbers[j - 1] = numbers[j];
numbers[j] = temp;
}
}
}
}
}`
System.out.println("\ninput 6 number between 1 and 40");
//Scanner is specifically designed for getting an input purpose and introduced in Java 5,so better use it
Scanner s = new Scanner(System.in);
//you need to have nested loop here
//But the best way to search is use binary search,as you have already sorted the array
while (s.hasNextInt()) {
//one at a time from the input is put to outcome
int outcome = s.nextInt();
boolean found = false;
for (int b = 0; b < 6; b++) {
found = false;
if (outcome == numbers[b]) {
found = true;
//remember to break the inner loop if a match is found
break;
} else {
found = false;
}
}
if (found == true) {
System.out.println("found in random numbers");
} else {
System.out.println("not found in random numbers");
}

Creating a Linked list with Structs - C++

I was writing a program which could read an input file and store the read data in nodes linked by a "link list". However, I was getting a few errors:
In constructor List::List(), no match for 'operator =' in *((List*)this)->List::list[0] = 0
In constructor Polynomial::Polynomial(): no match for 'operator =' in *((Polynomial*)this)->Polynomial::poly = (operator new(400u), (<statement>), ...)
I have a feeling where I do: I try to access a certain node through an array is where I go wrong, however, I can't figure it out much.
Here is the code:
#include <iostream>
#include <fstream>
using namespace std;
enum result{success, failure};
struct Node
{
double coefficient;
int power;
Node();
Node(double coef, int pwr);
};
struct List
{
Node *list[100];
//Default constructor
List();
};
Node::Node()
{
coefficient = 0;
power = 0;
}
List::List()
{
*list[0] = NULL;
}
Node::Node(double coef, int pwr)
{
coefficient = coef;
power = pwr;
}
class Polynomial
{
public:
Polynomial();
result multiply(Polynomial &p, Polynomial &q);
result add(Polynomial p, Polynomial &q);
void initialize(ifstream &file);
void simplify(Polynomial &var);
void print_poly();
~Polynomial();
private:
List *poly; //Store the pointer links in an array
Node first_node;
int val;
};
Polynomial::Polynomial()
{
*poly = new List();
}
Polynomial::void initialize(ifstream &file)
{
int y[20];
double x[20];
int i = 0, j = 0;
//Read from the file
file >> x[j];
file >> y[j];
first_node(x[j], y[j++]); //Create the first node with coef, and pwr
*poly->list[i] = &first_node; //Link to the fist node
//Creat a linked list
while(y[j] != 0)
{
file >> x[j];
file >> y[j];
*poly->list[++i] = new Node(x[j], y[j++]);
}
val = i+1; //Keeps track of the number of nodes
}
Polynomail::result multiply(Polynomial &p, Polynomial &q)
{
int i, j, k = 0;
for(i = 0; i < p.val; i++)
{
for(j = 0; j < q.val; j++)
{
*poly->list[k] = new Node(0, 0);
*poly->list[k].coefficient = (p.poly->list[i].coefficient)*(q.poly->list[j].coefficient);
*poly->list[k++].power = (p.poly->list[i].power)+(q.poly->list[j].power);
}
}
val = k+1; //Store the nunber of nodes
return success;
}
Polynomial::void simplify(Polynomial &var)
{
int i, j, k = 0;
//Create a copy of the polynomial
for(j = 0; j < var.val; j++)
{
*poly->list[j] = new Node(0, 0);
*poly->list[j].coefficient = var.poly->list[j].coefficient;
*poly->list[j].power = var.poly->list[j].power;
}
//Iterate through the nodes to find entries which have the same power and add them, otherwise do nothing
for(k = 0; k < var.val; k++)
{
for(i = k; i < var.val;)
{
if(*poly->list[k].power == var.poly->list[++i].power)
{
if(*poly->list.power[0] == 0)
{
NULL;
}
else
{
*poly->list[k].coefficient = *poly->list[k].coefficient + var.poly->list[i].ceofficient;
var.poly->list[i] = Node(0, 0);
}
}
}
}
}
Polynomial::void print_pol()
{
int i = 0;
for(i = 0; i < temp.val; i++)
{
cout << "Coefficient: " << temp.poly->list[i].coefficient << ", and " << "Power: " << temp.poly->list[i].power << endl;
}
}
The problem is a wrong dereference. Line 34 should probably be
list[0] = NULL; // remove the *
You try to assign the value NULL to a variable of the type Node, but you probably mean a pointer to Node.
The very same is true in line 63.
In addition, line 66 sould probably b:
void Polynomial::initialize(ifstream &file) // start with return type