Binary number

How do I create a 32 bit binary for a negative integer? Also, if I have an array of integer elements, if some of the elements are like say say 2^15 or (2^5)-1, is there a command that can take the calculated value , or do I have to calculate it seperately?

Comments

  • : How do I create a 32 bit binary for a negative integer? Also, if I
    : have an array of integer elements, if some of the elements are like
    : say say 2^15 or (2^5)-1, is there a command that can take the
    : calculated value , or do I have to calculate it seperately?
    :

    If you want to represent the negative value in binary, the easiest way involves using some bitwise operators.

    [code]
    int x = -5;

    // loop through bits printing out each digit
    for (int bit=31;bit>=0;bit--)
    {
    int val = (x >> bit)&1;
    // shift bits right by value of "bit" and mask down to the 1's digit
    // in matlab, this could be done using: val = bitand(bitshift(x,-bit),1)
    // val is either 0 or 1.
    printf("%d",val);
    // print out the digit as a single '0' or '1'
    // matlab: disp(sprintf("%d",val));
    }

    // output example: 111111111111111111111111111011

    [/code]

    It might be helpful to look at the bitwise operators in MatLab.
    http://matlab.izmiran.ru/help/techdoc/ref/bitshift.html
    http://matlab.izmiran.ru/help/techdoc/ref/bitand.html
  • Oh I didnt think about bitshift. I was trying to use XOR + OR with 1. it didnt work for 32 bits.
    Anyways, what about the second part?

    if I have an array of integer elements, if some of the elements are like say say 2^15 or (2^5)-1, is there a command that can take the calculated value , or do I have to calculate it seperately?
  • Ive tried bitand and bitshift, but it doesnt give me the correct 32 bit binary sequence for a negative integer.

    Ive figure about the second part. But I need help in building binary for negative ints.
    Please reply.
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories