Negative integer to binary in Golang [duplicate]











up vote
1
down vote

favorite
1













This question already has an answer here:




  • Format printing the 64bit integer -1 as hexadecimal deviates between golang and C [closed]

    3 answers




How can a negative integer be represented as a binary in Go, using the two's complement notation?

For example:



n := int64(-1)
fmt.Printf("%b", n)
fmt.Println(strconv.FormatInt(n, 2))


Both lines print -1. The result shoud be like ffffffffffffffff.










share|improve this question













marked as duplicate by Flimzy, icza go
Users with the  go badge can single-handedly close go questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Nov 11 at 10:07


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.



















    up vote
    1
    down vote

    favorite
    1













    This question already has an answer here:




    • Format printing the 64bit integer -1 as hexadecimal deviates between golang and C [closed]

      3 answers




    How can a negative integer be represented as a binary in Go, using the two's complement notation?

    For example:



    n := int64(-1)
    fmt.Printf("%b", n)
    fmt.Println(strconv.FormatInt(n, 2))


    Both lines print -1. The result shoud be like ffffffffffffffff.










    share|improve this question













    marked as duplicate by Flimzy, icza go
    Users with the  go badge can single-handedly close go questions as duplicates and reopen them as needed.

    StackExchange.ready(function() {
    if (StackExchange.options.isMobile) return;

    $('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
    var $hover = $(this).addClass('hover-bound'),
    $msg = $hover.siblings('.dupe-hammer-message');

    $hover.hover(
    function() {
    $hover.showInfoMessage('', {
    messageElement: $msg.clone().show(),
    transient: false,
    position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
    dismissable: false,
    relativeToBody: true
    });
    },
    function() {
    StackExchange.helpers.removeMessages();
    }
    );
    });
    });
    Nov 11 at 10:07


    This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

















      up vote
      1
      down vote

      favorite
      1









      up vote
      1
      down vote

      favorite
      1






      1






      This question already has an answer here:




      • Format printing the 64bit integer -1 as hexadecimal deviates between golang and C [closed]

        3 answers




      How can a negative integer be represented as a binary in Go, using the two's complement notation?

      For example:



      n := int64(-1)
      fmt.Printf("%b", n)
      fmt.Println(strconv.FormatInt(n, 2))


      Both lines print -1. The result shoud be like ffffffffffffffff.










      share|improve this question














      This question already has an answer here:




      • Format printing the 64bit integer -1 as hexadecimal deviates between golang and C [closed]

        3 answers




      How can a negative integer be represented as a binary in Go, using the two's complement notation?

      For example:



      n := int64(-1)
      fmt.Printf("%b", n)
      fmt.Println(strconv.FormatInt(n, 2))


      Both lines print -1. The result shoud be like ffffffffffffffff.





      This question already has an answer here:




      • Format printing the 64bit integer -1 as hexadecimal deviates between golang and C [closed]

        3 answers








      go binary numeric twos-complement






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 11 at 5:41









      Radoslav Stoyanov

      69731633




      69731633




      marked as duplicate by Flimzy, icza go
      Users with the  go badge can single-handedly close go questions as duplicates and reopen them as needed.

      StackExchange.ready(function() {
      if (StackExchange.options.isMobile) return;

      $('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
      var $hover = $(this).addClass('hover-bound'),
      $msg = $hover.siblings('.dupe-hammer-message');

      $hover.hover(
      function() {
      $hover.showInfoMessage('', {
      messageElement: $msg.clone().show(),
      transient: false,
      position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
      dismissable: false,
      relativeToBody: true
      });
      },
      function() {
      StackExchange.helpers.removeMessages();
      }
      );
      });
      });
      Nov 11 at 10:07


      This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.






      marked as duplicate by Flimzy, icza go
      Users with the  go badge can single-handedly close go questions as duplicates and reopen them as needed.

      StackExchange.ready(function() {
      if (StackExchange.options.isMobile) return;

      $('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
      var $hover = $(this).addClass('hover-bound'),
      $msg = $hover.siblings('.dupe-hammer-message');

      $hover.hover(
      function() {
      $hover.showInfoMessage('', {
      messageElement: $msg.clone().show(),
      transient: false,
      position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
      dismissable: false,
      relativeToBody: true
      });
      },
      function() {
      StackExchange.helpers.removeMessages();
      }
      );
      });
      });
      Nov 11 at 10:07


      This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.


























          2 Answers
          2






          active

          oldest

          votes

















          up vote
          2
          down vote













          I am sorry but did you mean you wanted to explore how int64 values are stored in the memory? You will need to use the unsafe package to force reinterpret a value in go.



          This code does what you want:



          package main

          import (
          "fmt"
          "unsafe"
          )

          func main() {
          a := int64(-1)
          fmt.Printf("%xn", *(*[8]byte)(unsafe.Pointer(&a)))
          }





          share|improve this answer





















          • Wow! It seems to be working, but... isn't there some more fancy way of doing it as in the other languages? :)
            – Radoslav Stoyanov
            Nov 11 at 6:07










          • Golang is a type-safe language which means that it does not allow you to interpret values to an incompatible type(int64 to raw bytes in this case), which is not the case in "other languages" such as C. If you really needed to do so you will have to use the unsafe package to circumvent this protection.
            – Eternal_flame-AD
            Nov 11 at 6:11






          • 1




            Don't use package unsafe for this, simply convert it to unsigned integer as presented in the marked duplicate. Only use unsafe if truly justified, and only as a last resort.
            – icza
            Nov 11 at 10:10


















          up vote
          0
          down vote













          I also wrote a func to programmatically calculate the two's complement notation of a int64 in case that you just wanted to calculate the value:



          package main

          import (
          "fmt"
          "math/big"
          )

          func main() {
          a := int64(-1)
          fmt.Printf("%xn", TwoComplement(a))
          }

          func TwoComplement(val int64) byte {
          n := big.NewInt(val)

          var r byte
          if n.Cmp(big.NewInt(0)) != -1 {
          r = n.Bytes()
          } else {
          mask := big.NewInt(1)
          mask.Lsh(mask, 64)

          r = n.Add(n, mask).Bytes()
          }

          res := bytes.NewBuffer(byte{})
          for i := 0; i < 8-len(r); i++ {
          res.WriteByte(0)
          }
          res.Write(r)
          return res.Bytes()
          }





          share|improve this answer






























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            2
            down vote













            I am sorry but did you mean you wanted to explore how int64 values are stored in the memory? You will need to use the unsafe package to force reinterpret a value in go.



            This code does what you want:



            package main

            import (
            "fmt"
            "unsafe"
            )

            func main() {
            a := int64(-1)
            fmt.Printf("%xn", *(*[8]byte)(unsafe.Pointer(&a)))
            }





            share|improve this answer





















            • Wow! It seems to be working, but... isn't there some more fancy way of doing it as in the other languages? :)
              – Radoslav Stoyanov
              Nov 11 at 6:07










            • Golang is a type-safe language which means that it does not allow you to interpret values to an incompatible type(int64 to raw bytes in this case), which is not the case in "other languages" such as C. If you really needed to do so you will have to use the unsafe package to circumvent this protection.
              – Eternal_flame-AD
              Nov 11 at 6:11






            • 1




              Don't use package unsafe for this, simply convert it to unsigned integer as presented in the marked duplicate. Only use unsafe if truly justified, and only as a last resort.
              – icza
              Nov 11 at 10:10















            up vote
            2
            down vote













            I am sorry but did you mean you wanted to explore how int64 values are stored in the memory? You will need to use the unsafe package to force reinterpret a value in go.



            This code does what you want:



            package main

            import (
            "fmt"
            "unsafe"
            )

            func main() {
            a := int64(-1)
            fmt.Printf("%xn", *(*[8]byte)(unsafe.Pointer(&a)))
            }





            share|improve this answer





















            • Wow! It seems to be working, but... isn't there some more fancy way of doing it as in the other languages? :)
              – Radoslav Stoyanov
              Nov 11 at 6:07










            • Golang is a type-safe language which means that it does not allow you to interpret values to an incompatible type(int64 to raw bytes in this case), which is not the case in "other languages" such as C. If you really needed to do so you will have to use the unsafe package to circumvent this protection.
              – Eternal_flame-AD
              Nov 11 at 6:11






            • 1




              Don't use package unsafe for this, simply convert it to unsigned integer as presented in the marked duplicate. Only use unsafe if truly justified, and only as a last resort.
              – icza
              Nov 11 at 10:10













            up vote
            2
            down vote










            up vote
            2
            down vote









            I am sorry but did you mean you wanted to explore how int64 values are stored in the memory? You will need to use the unsafe package to force reinterpret a value in go.



            This code does what you want:



            package main

            import (
            "fmt"
            "unsafe"
            )

            func main() {
            a := int64(-1)
            fmt.Printf("%xn", *(*[8]byte)(unsafe.Pointer(&a)))
            }





            share|improve this answer












            I am sorry but did you mean you wanted to explore how int64 values are stored in the memory? You will need to use the unsafe package to force reinterpret a value in go.



            This code does what you want:



            package main

            import (
            "fmt"
            "unsafe"
            )

            func main() {
            a := int64(-1)
            fmt.Printf("%xn", *(*[8]byte)(unsafe.Pointer(&a)))
            }






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 11 at 6:02









            Eternal_flame-AD

            3126




            3126












            • Wow! It seems to be working, but... isn't there some more fancy way of doing it as in the other languages? :)
              – Radoslav Stoyanov
              Nov 11 at 6:07










            • Golang is a type-safe language which means that it does not allow you to interpret values to an incompatible type(int64 to raw bytes in this case), which is not the case in "other languages" such as C. If you really needed to do so you will have to use the unsafe package to circumvent this protection.
              – Eternal_flame-AD
              Nov 11 at 6:11






            • 1




              Don't use package unsafe for this, simply convert it to unsigned integer as presented in the marked duplicate. Only use unsafe if truly justified, and only as a last resort.
              – icza
              Nov 11 at 10:10


















            • Wow! It seems to be working, but... isn't there some more fancy way of doing it as in the other languages? :)
              – Radoslav Stoyanov
              Nov 11 at 6:07










            • Golang is a type-safe language which means that it does not allow you to interpret values to an incompatible type(int64 to raw bytes in this case), which is not the case in "other languages" such as C. If you really needed to do so you will have to use the unsafe package to circumvent this protection.
              – Eternal_flame-AD
              Nov 11 at 6:11






            • 1




              Don't use package unsafe for this, simply convert it to unsigned integer as presented in the marked duplicate. Only use unsafe if truly justified, and only as a last resort.
              – icza
              Nov 11 at 10:10
















            Wow! It seems to be working, but... isn't there some more fancy way of doing it as in the other languages? :)
            – Radoslav Stoyanov
            Nov 11 at 6:07




            Wow! It seems to be working, but... isn't there some more fancy way of doing it as in the other languages? :)
            – Radoslav Stoyanov
            Nov 11 at 6:07












            Golang is a type-safe language which means that it does not allow you to interpret values to an incompatible type(int64 to raw bytes in this case), which is not the case in "other languages" such as C. If you really needed to do so you will have to use the unsafe package to circumvent this protection.
            – Eternal_flame-AD
            Nov 11 at 6:11




            Golang is a type-safe language which means that it does not allow you to interpret values to an incompatible type(int64 to raw bytes in this case), which is not the case in "other languages" such as C. If you really needed to do so you will have to use the unsafe package to circumvent this protection.
            – Eternal_flame-AD
            Nov 11 at 6:11




            1




            1




            Don't use package unsafe for this, simply convert it to unsigned integer as presented in the marked duplicate. Only use unsafe if truly justified, and only as a last resort.
            – icza
            Nov 11 at 10:10




            Don't use package unsafe for this, simply convert it to unsigned integer as presented in the marked duplicate. Only use unsafe if truly justified, and only as a last resort.
            – icza
            Nov 11 at 10:10












            up vote
            0
            down vote













            I also wrote a func to programmatically calculate the two's complement notation of a int64 in case that you just wanted to calculate the value:



            package main

            import (
            "fmt"
            "math/big"
            )

            func main() {
            a := int64(-1)
            fmt.Printf("%xn", TwoComplement(a))
            }

            func TwoComplement(val int64) byte {
            n := big.NewInt(val)

            var r byte
            if n.Cmp(big.NewInt(0)) != -1 {
            r = n.Bytes()
            } else {
            mask := big.NewInt(1)
            mask.Lsh(mask, 64)

            r = n.Add(n, mask).Bytes()
            }

            res := bytes.NewBuffer(byte{})
            for i := 0; i < 8-len(r); i++ {
            res.WriteByte(0)
            }
            res.Write(r)
            return res.Bytes()
            }





            share|improve this answer



























              up vote
              0
              down vote













              I also wrote a func to programmatically calculate the two's complement notation of a int64 in case that you just wanted to calculate the value:



              package main

              import (
              "fmt"
              "math/big"
              )

              func main() {
              a := int64(-1)
              fmt.Printf("%xn", TwoComplement(a))
              }

              func TwoComplement(val int64) byte {
              n := big.NewInt(val)

              var r byte
              if n.Cmp(big.NewInt(0)) != -1 {
              r = n.Bytes()
              } else {
              mask := big.NewInt(1)
              mask.Lsh(mask, 64)

              r = n.Add(n, mask).Bytes()
              }

              res := bytes.NewBuffer(byte{})
              for i := 0; i < 8-len(r); i++ {
              res.WriteByte(0)
              }
              res.Write(r)
              return res.Bytes()
              }





              share|improve this answer

























                up vote
                0
                down vote










                up vote
                0
                down vote









                I also wrote a func to programmatically calculate the two's complement notation of a int64 in case that you just wanted to calculate the value:



                package main

                import (
                "fmt"
                "math/big"
                )

                func main() {
                a := int64(-1)
                fmt.Printf("%xn", TwoComplement(a))
                }

                func TwoComplement(val int64) byte {
                n := big.NewInt(val)

                var r byte
                if n.Cmp(big.NewInt(0)) != -1 {
                r = n.Bytes()
                } else {
                mask := big.NewInt(1)
                mask.Lsh(mask, 64)

                r = n.Add(n, mask).Bytes()
                }

                res := bytes.NewBuffer(byte{})
                for i := 0; i < 8-len(r); i++ {
                res.WriteByte(0)
                }
                res.Write(r)
                return res.Bytes()
                }





                share|improve this answer














                I also wrote a func to programmatically calculate the two's complement notation of a int64 in case that you just wanted to calculate the value:



                package main

                import (
                "fmt"
                "math/big"
                )

                func main() {
                a := int64(-1)
                fmt.Printf("%xn", TwoComplement(a))
                }

                func TwoComplement(val int64) byte {
                n := big.NewInt(val)

                var r byte
                if n.Cmp(big.NewInt(0)) != -1 {
                r = n.Bytes()
                } else {
                mask := big.NewInt(1)
                mask.Lsh(mask, 64)

                r = n.Add(n, mask).Bytes()
                }

                res := bytes.NewBuffer(byte{})
                for i := 0; i < 8-len(r); i++ {
                res.WriteByte(0)
                }
                res.Write(r)
                return res.Bytes()
                }






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Nov 11 at 7:23

























                answered Nov 11 at 7:14









                Eternal_flame-AD

                3126




                3126















                    Popular posts from this blog

                    Full-time equivalent

                    さくらももこ

                    13 indicted, 8 arrested in Calif. drug cartel investigation