dimanche 30 juillet 2017

change positive numbers of array into their negative alternative with bitwise operations

I am trying change positive elements of array into their negative alternative with bitwise operations.I wrote this but its not working. I can't understand why. Can someone help me? thanks!

#include <iostream>
using namespace std;
#define n 5
void shecvla(int x)
{
  int k = sizeof(int) * 8, m = 1;
  for (int i = 0; i < k; i++)
    m <<= 1;
  if ((x & m) == 0)
    ~(x) + 1;
}

void alternativa(int a[], int k)
{
  for (int i = 0; i < k; i++)
    shecvla(a[i]);
}

void orobiti(int s)
{
  unsigned int m = 1;
  int k = sizeof(int) * 8;
  for (int i = 0; i < k - 1; i++)
    m <<= 1;
  for (int i = 0; i < k; i++) {
    if ((s & m) != 0)
      cout << 1;
    else
      cout << 0;
    m >>= 1;
  }
  cout << endl;
}

void print(int a[], int k)
{
  for (int i = 0; i < k; i++)
    orobiti(a[i]);
}

main()
{
  int a[n];
  for (int i = 0; i < n; i++)
    cin >> a[i];
  print(a, n);
  alternativa(a, n);
  cout << endl;
  print(a, n);
  for (int i = 0; i < n; i++)
    cout << a[i] << " ";
  system("pause");
  return 0;
}

Aucun commentaire:

Enregistrer un commentaire