Binary number - Programmers Heaven

Howdy, Stranger!

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

Categories

Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

Binary number

rosh72851rosh72851 Posts: 4Member
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

  • Josh CodeJosh Code Posts: 675Member
    : 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
  • rosh72851rosh72851 Posts: 4Member
    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?
  • rosh72851rosh72851 Posts: 4Member
    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.