<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Vladimir Vivien</title>
    <description>The latest articles on DEV Community by Vladimir Vivien (@vladimirvivien).</description>
    <link>https://dev.to/vladimirvivien</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F2734%2F309126.jpeg</url>
      <title>DEV Community: Vladimir Vivien</title>
      <link>https://dev.to/vladimirvivien</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/vladimirvivien"/>
    <language>en</language>
    <item>
      <title>Calling Go Functions from Other Languages</title>
      <dc:creator>Vladimir Vivien</dc:creator>
      <pubDate>Mon, 27 Feb 2017 19:05:26 +0000</pubDate>
      <link>https://dev.to/vladimirvivien/calling-go-functions-from-other-languages</link>
      <guid>https://dev.to/vladimirvivien/calling-go-functions-from-other-languages</guid>
      <description>&lt;p&gt;Starting with version 1.5, the Go compiler introduced support for several build modes via the &lt;code&gt;-buildmode&lt;/code&gt; flag. Known as the &lt;a href="https://docs.google.com/document/d/1nr-TQHw_er6GOQRsF6T43GGhFDelrAP0NqSS_00RgZQ/edit" rel="noopener noreferrer"&gt;&lt;em&gt;Go Execution Modes&lt;/em&gt;&lt;/a&gt;, these build modes extended the go tool to compile Go packages into several formats including Go archives, Go shared libraries, C archives, C shared libraries, and (introduced in 1.8) Go dynamic plugins.&lt;/p&gt;

&lt;p&gt;This post is about compiling Go packages into C shared libraries. With this build mode, the compiler outputs a standard shared object binary file (&lt;code&gt;.so&lt;/code&gt;) exposing Go functions as a C-style APIs. Here we discuss how to create Go libraries that can be called from &lt;em&gt;C&lt;/em&gt;, &lt;em&gt;Python&lt;/em&gt;, &lt;em&gt;Ruby&lt;/em&gt;, &lt;em&gt;Node&lt;/em&gt;, and &lt;em&gt;Java&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;All source code discussed here can be found on &lt;a href="https://github.com/vladimirvivien/go-cshared-examples" rel="noopener noreferrer"&gt;GitHub&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Go Code
&lt;/h2&gt;

&lt;p&gt;First, let us write the Go code. Assume that we have written an &lt;code&gt;awesome&lt;/code&gt; Go library that we want to make available to other languages. There are four requirements to follow before compiling the code into a shared library: &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The package must be a &lt;code&gt;main&lt;/code&gt;  package. The compiler will build the package and all of its dependencies into a single shared object binary.&lt;/li&gt;
&lt;li&gt;The source must import the pseudo-package &lt;code&gt;"C"&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Use the &lt;code&gt;//export&lt;/code&gt; comment to annotate functions you wish to make accessible to other languages.&lt;/li&gt;
&lt;li&gt;An empty &lt;code&gt;main&lt;/code&gt; function must be declared.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The following Go source exports four functions &lt;code&gt;Add&lt;/code&gt;, &lt;code&gt;Cosine&lt;/code&gt;, &lt;code&gt;Sort&lt;/code&gt;, and &lt;code&gt;Log&lt;/code&gt;. Admittedly, the awesome library is not that impressive. However, its diverse function signatures will help us explore type mapping implications.&lt;/p&gt;

&lt;p&gt;File &lt;a href="https://github.com/vladimirvivien/go-cshared-examples/blob/master/awesome.go" rel="noopener noreferrer"&gt;awesome.go&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package main

import "C"

import (
    "fmt"
    "math"
    "sort"
    "sync"
)

var count int
var mtx sync.Mutex

//export Add
func Add(a, b int) int {
    return a + b
}

//export Cosine
func Cosine(x float64) float64 {
    return math.Cos(x)
}

//export Sort
func Sort(vals []int) {
    sort.Ints(vals)
}

//export Log
func Log(msg string) int {
    mtx.Lock()
    defer mtx.Unlock()
    fmt.Println(msg)
    count++
    return count
}

func main() {}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The package is compiled using the &lt;code&gt;-buildmode=c-shared&lt;/code&gt; build flag to create the shared object binary:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;go build -o awesome.so -buildmode=c-shared awesome.go
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Upon completion, the compiler outputs two files: &lt;code&gt;awesome.h&lt;/code&gt;, a C header file and &lt;code&gt;awesome.so&lt;/code&gt;, the shared object file, shown below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-rw-rw-r –    1362 Feb 11 07:59 awesome.h
-rw-rw-r – 1997880 Feb 11 07:59 awesome.so
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Notice that the &lt;code&gt;.so&lt;/code&gt; file is around 2 Mb, relatively large for such a small library. This is because the entire Go runtime machinery and dependent packages are crammed into a single shared object binary (similar to compiling a single static executable binary).&lt;/p&gt;

&lt;h3&gt;
  
  
  The header file
&lt;/h3&gt;

&lt;p&gt;The header file defines C types mapped to Go compatible types using &lt;a href="https://golang.org/cmd/cgo/" rel="noopener noreferrer"&gt;cgo&lt;/a&gt; semantics.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/* Created by “go tool cgo” – DO NOT EDIT. */
...
typedef long long GoInt64;
typedef unsigned long long GoUint64;
typedef GoInt64 GoInt;
typedef double GoFloat64;
...
typedef struct { const char *p; GoInt n; } GoString;
typedef struct { void *data; GoInt len; GoInt cap; } GoSlice;
...
#endif
...
extern GoInt Add(GoInt p0, GoInt p1);
extern GoFloat64 Cosine(GoFloat64 p0);
extern void Sort(GoSlice p0);
extern GoInt Log(GoString p0);
...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  The shared object file
&lt;/h3&gt;

&lt;p&gt;The other file generated by the compiler is a &lt;code&gt;64-bit ELF&lt;/code&gt; shared object binary file. We can verify its information using the &lt;code&gt;file&lt;/code&gt; command.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$&amp;gt; file awesome.so
awesome.so: ELF 64-bit LSB shared object, x86–64, version 1 (SYSV), dynamically linked, BuildID[sha1]=1fcf29a2779a335371f17219fffbdc47b2ed378a, not stripped
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Using the &lt;code&gt;nm&lt;/code&gt; and the &lt;code&gt;grep&lt;/code&gt; commands, we can ensure our Go functions got exported in the shared object file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$&amp;gt; nm awesome.so | grep -e "T Add" -e "T Cosine" -e "T Sort" -e "T Log"
00000000000d0db0 T Add
00000000000d0e30 T Cosine
00000000000d0f30 T Log
00000000000d0eb0 T Sort
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  From C
&lt;/h2&gt;

&lt;p&gt;There are two ways to use the shared object library to call Go functions from C. First, we can statically bind the shared library at compilation, but dynamically link it at runtime. Or, have the Go function symbols be dynamically loaded and bound at runtime.&lt;/p&gt;

&lt;h3&gt;
  
  
  Dynamically linked
&lt;/h3&gt;

&lt;p&gt;In this approach, we use the header file to statically reference types and functions exported in the shared object file. The code is simple and clean as shown below (some print statements omitted):&lt;/p&gt;

&lt;p&gt;File &lt;a href="https://github.com/vladimirvivien/go-cshared-examples/blob/master/client1.c" rel="noopener noreferrer"&gt;client1.c&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#include &amp;lt;stdio.h&amp;gt;
#include "awesome.h"

int main() {
    printf("Using awesome lib from C:\n");

    GoInt a = 12;
    GoInt b = 99;
    printf("awesome.Add(12,99) = %d\n", Add(a, b)); 
    printf("awesome.Cosine(1) = %f\n", (float)(Cosine(1.0)));

    GoInt data[6] = {77, 12, 5, 99, 28, 23};
    GoSlice nums = {data, 6, 6};
    Sort(nums);
    ...
    GoString msg = {"Hello from C!", 13};
    Log(msg);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next we compile the C code, specifying the shared object library:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$&amp;gt; gcc -o client client1.c ./awesome.so
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When the resulting binary is executed, it links to the awesome.so library, calling the functions that were exported from Go as the output shows below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$&amp;gt; ./client
awesome.Add(12,99) = 111
awesome.Cosine(1) = 0.540302
awesome.Sort(77,12,5,99,28,23): 5,12,23,28,77,99,
Hello from C!
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Dynamically Loaded
&lt;/h3&gt;

&lt;p&gt;In this approach, the C code uses the dynamic link loader library (&lt;code&gt;libdl.so&lt;/code&gt;) to dynamically load and bind exported symbols. It uses functions defined in &lt;code&gt;dhfcn.h&lt;/code&gt; such as &lt;code&gt;dlopen&lt;/code&gt; to open the library file, &lt;code&gt;dlsym&lt;/code&gt; to look up a symbol, &lt;code&gt;dlerror&lt;/code&gt; to retrieve errors, and &lt;code&gt;dlclose&lt;/code&gt; to close the shared library file.&lt;/p&gt;

&lt;p&gt;Because the binding and linking is done in your source code, this version is lengthier. However, it is doing the same thing as before, as highlighted in the following snippet (some print statements and error handling omitted).&lt;/p&gt;

&lt;p&gt;File &lt;a href="https://github.com/vladimirvivien/go-cshared-examples/blob/master/client2.c" rel="noopener noreferrer"&gt;client2.c&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#include &amp;lt;stdlib.h&amp;gt;
#include &amp;lt;stdio.h&amp;gt;
#include &amp;lt;dlfcn.h&amp;gt;

// define types needed
typedef long long go_int;
typedef double go_float64;
typedef struct{void *arr; go_int len; go_int cap;} go_slice;
typedef struct{const char *p; go_int len;} go_str;

int main(int argc, char **argv) {
    void *handle;
    char *error;

    handle = dlopen ("./awesome.so", RTLD_LAZY);
    if (!handle) {
        fputs (dlerror(), stderr);
        exit(1);
    }

    go_int (*add)(go_int, go_int)  = dlsym(handle, "Add");
    if ((error = dlerror()) != NULL)  { ... }
    go_int sum = (*add)(12, 99); 
    printf("awesome.Add(12, 99) = %d\n", sum);

    go_float64 (*cosine)(go_float64) = dlsym(handle, "Cosine");
    go_float64 cos = (*cosine)(1.0);
    printf("awesome.Cosine(1) = %f\n", cos);

    void (*sort)(go_slice) = dlsym(handle, "Sort");
    go_int data[5] = {44,23,7,66,2};
    go_slice nums = {data, 5, 5};
    sort(nums);

    go_int (*log)(go_str) = dlsym(handle, "Log");
    go_str msg = {"Hello from C!", 13};
    log(msg);

    dlclose(handle);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the previous code, we define our own subset of Go compatible C types &lt;code&gt;go_int&lt;/code&gt;, &lt;code&gt;go_float&lt;/code&gt;, &lt;code&gt;go_slice&lt;/code&gt;, and &lt;code&gt;go_str&lt;/code&gt;. We use &lt;code&gt;dlsym&lt;/code&gt; to load symbols &lt;code&gt;Add&lt;/code&gt;, &lt;code&gt;Cosine&lt;/code&gt;, &lt;code&gt;Sort&lt;/code&gt;, and &lt;code&gt;Log&lt;/code&gt; and assign them to their respective function pointers. Next, we compile the code linking it with the &lt;code&gt;dl&lt;/code&gt; library (not the awesome.so) as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$&amp;gt; gcc -o client client2.c -ldl
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When the code is executed, the C binary loads and links to shared library awesome.so producing the following output:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$&amp;gt; ./client
awesome.Add(12, 99) = 111
awesome.Cosine(1) = 0.540302
awesome.Sort(44,23,7,66,2): 2,7,23,44,66,
Hello from C!
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  From Python
&lt;/h2&gt;

&lt;p&gt;In Python things get a little easier. We use the &lt;code&gt;ctypes&lt;/code&gt; &lt;a href="https://docs.python.org/3/library/ctypes.html" rel="noopener noreferrer"&gt;foreign function library&lt;/a&gt; to call Go functions from the the awesome.so shared library as shown in the following snippet (some print statements are omitted).&lt;/p&gt;

&lt;p&gt;File &lt;a href="https://github.com/vladimirvivien/go-cshared-examples/blob/master/client.py" rel="noopener noreferrer"&gt;client.py&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from ctypes import *

lib = cdll.LoadLibrary("./awesome.so")
lib.Add.argtypes = [c_longlong, c_longlong]
print "awesome.Add(12,99) = %d" % lib.Add(12,99)

lib.Cosine.argtypes = [c_double]
lib.Cosine.restype = c_double 
cos = lib.Cosine(1)
print "awesome.Cosine(1) = %f" % cos

class GoSlice(Structure):
    _fields_ = [("data", POINTER(c_void_p)), 
                ("len", c_longlong), ("cap", c_longlong)]

nums = GoSlice((c_void_p * 5)(74, 4, 122, 9, 12), 5, 5)
lib.Sort.argtypes = [GoSlice]
lib.Sort.restype = None
lib.Sort(nums)

class GoString(Structure):
    _fields_ = [("p", c_char_p), ("n", c_longlong)]

lib.Log.argtypes = [GoString]
msg = GoString(b"Hello Python!", 13)
lib.Log(msg)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note the &lt;code&gt;lib&lt;/code&gt; variable represents the loaded symbols from the shared object file. We also defined Python classes &lt;code&gt;GoString&lt;/code&gt; and &lt;code&gt;GoSlice&lt;/code&gt; to map to their respective C struct types. When the Python code is executed, it calls the Go functions in the shared object producing the following output:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$&amp;gt; python client.py
awesome.Add(12,99) = 111
awesome.Cosine(1) = 0.540302
awesome.Sort(74,4,122,9,12) = [ 4 9 12 74 122 ]
Hello Python!
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  From Ruby
&lt;/h2&gt;

&lt;p&gt;Calling Go functions from Ruby follows a similar pattern as above. We use the the &lt;a href="https://github.com/ffi/ffi" rel="noopener noreferrer"&gt;FFI gem&lt;/a&gt; to dynamically load and call exported Go functions in the awesome.so shared object file as shown in the following snippet.&lt;/p&gt;

&lt;p&gt;File &lt;a href="https://github.com/vladimirvivien/go-cshared-examples/blob/master/client.rb" rel="noopener noreferrer"&gt;client.rb&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;require 'ffi'

module Awesome
  extend FFI::Library

  ffi_lib './awesome.so'

  class GoSlice &amp;lt; FFI::Struct
    layout :data,  :pointer,
           :len,   :long_long,
           :cap,   :long_long
  end

  class GoString &amp;lt; FFI::Struct
    layout :p,     :pointer,
           :len,   :long_long
  end

  attach_function :Add, [:long_long, :long_long], :long_long
  attach_function :Cosine, [:double], :double
  attach_function :Sort, [GoSlice.by_value], :void
  attach_function :Log, [GoString.by_value], :int
end

print "awesome.Add(12, 99) = ",  Awesome.Add(12, 99), "\n"
print "awesome.Cosine(1) = ", Awesome.Cosine(1), "\n"

nums = [92,101,3,44,7]
ptr = FFI::MemoryPointer.new :long_long, nums.size
ptr.write_array_of_long_long  nums
slice = Awesome::GoSlice.new
slice[:data] = ptr
slice[:len] = nums.size
slice[:cap] = nums.size
Awesome.Sort(slice)

msg = "Hello Ruby!"
gostr = Awesome::GoString.new
gostr[:p] = FFI::MemoryPointer.from_string(msg)
gostr[:len] = msg.size
Awesome.Log(gostr)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In Ruby, we must extend the &lt;code&gt;FFI&lt;/code&gt; module to declare the symbols being loaded from the shared library. We use Ruby classes &lt;code&gt;GoSlice&lt;/code&gt; and &lt;code&gt;GoString&lt;/code&gt; to map the respective C structs. When we run the code it calls the exported Go functions as shown below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$&amp;gt; ruby client.rb
awesome.Add(12, 99) = 111
awesome.Cosine(1) = 0.5403023058681398
awesome.Sort([92, 101, 3, 44, 7]) = [3, 7, 44, 92, 101]
Hello Ruby!
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  From Node
&lt;/h2&gt;

&lt;p&gt;For Node, we use a foreign function library called &lt;a href="https://github.com/node-ffi/node-ffi" rel="noopener noreferrer"&gt;node-ffi&lt;/a&gt; (and a couple dependent packages) to dynamically load and call exported Go functions in the awesome.so shared object file as shown in the following snippet:&lt;/p&gt;

&lt;p&gt;File &lt;a href="https://github.com/vladimirvivien/go-cshared-examples/blob/master/client.js" rel="noopener noreferrer"&gt;client.js&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var ref = require("ref");
var ffi = require("ffi");
var Struct = require("ref-struct");
var ArrayType = require("ref-array");

var LongArray = ArrayType(ref.types.longlong);

var GoSlice = Struct({
  data: LongArray,
  len:  "longlong",
  cap: "longlong"
});

var GoString = Struct({
  p: "string",
  n: "longlong"
});

var awesome = ffi.Library("./awesome.so", {
  Add: ["longlong", ["longlong", "longlong"]],
  Cosine: ["double", ["double"]],
  Sort: ["void", [GoSlice]],
  Log: ["longlong", [GoString]]
});

console.log("awesome.Add(12, 99) = ", awesome.Add(12, 99));
console.log("awesome.Cosine(1) = ", awesome.Cosine(1));

nums = LongArray([12,54,0,423,9]);
var slice = new GoSlice();
slice["data"] = nums;
slice["len"] = 5;
slice["cap"] = 5;
awesome.Sort(slice);

str = new GoString();
str["p"] = "Hello Node!";
str["n"] = 11;
awesome.Log(str);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Node uses the &lt;code&gt;ffi&lt;/code&gt; object to declare the loaded symbols from the shared library . We also use Node struct objects &lt;code&gt;GoSlice&lt;/code&gt; and &lt;code&gt;GoString&lt;/code&gt; to map to their respective C structs. When we run the code it calls the exported Go functions as shown below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;awesome.Add(12, 99) =  111
awesome.Cosine(1) =  0.5403023058681398
awesome.Sort([12,54,9,423,9] =  [ 0, 9, 12, 54, 423 ]
Hello Node!
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  From Java
&lt;/h2&gt;

&lt;p&gt;To call the exported Go functions from Java, we use the &lt;a href="https://github.com/java-native-access/jna" rel="noopener noreferrer"&gt;Java Native Access library&lt;/a&gt; or JNA as shown in the following code snippet (with some statements omitted or abbreviated):&lt;/p&gt;

&lt;p&gt;File &lt;a href="https://github.com/vladimirvivien/go-cshared-examples/blob/master/Client.java" rel="noopener noreferrer"&gt;Client.java&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import com.sun.jna.*;

public class Client {
  public interface Awesome extends Library {
    public class GoSlice extends Structure {
      ...
      public Pointer data;
      public long len;
      public long cap;
    }

    public class GoString extends Structure {
      ...
      public String p;
      public long n;
    }

    public long Add(long a, long b);
    public double Cosine(double val);
    public void Sort(GoSlice.ByValue vals);
    public long Log(GoString.ByValue str);
  }

  static public void main(String argv[]) {
    Awesome awesome = (Awesome) Native.loadLibrary(
      "./awesome.so", Awesome.class);

    System.out.printf(... awesome.Add(12, 99));
    System.out.printf(... awesome.Cosine(1.0));

    long[] nums = new long[]{53,11,5,2,88};
    Memory arr = new Memory(... Native.getNativeSize(Long.TYPE));
    Awesome.GoSlice.ByValue slice = new Awesome.GoSlice.ByValue();
    slice.data = arr;
    slice.len = nums.length;
    slice.cap = nums.length;
    awesome.Sort(slice);

    Awesome.GoString.ByValue str = new Awesome.GoString.ByValue();
    str.p = "Hello Java!";
    str.n = str.p.length();
    awesome.Log(str);
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To use JNA, we define Java interface &lt;code&gt;Awesome&lt;/code&gt; to represents the symbols loaded from the awesome.so shared library file. We also declare classes &lt;code&gt;GoSlice&lt;/code&gt; and &lt;code&gt;GoString&lt;/code&gt; to map to their respective C struct representations. When we compile and run the code, it calls the exported Go functions as shown below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$&amp;gt; javac -cp jna.jar Client.java
$&amp;gt; java -cp .:jna.jar Client
awesome.Add(12, 99) = 111
awesome.Cosine(1.0) = 0.5403023058681398
awesome.Sort(53,11,5,2,88) = [2 5 11 53 88 ]
Hello Java!
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;This post showed how to create a Go library that can be used from other languages. By compiling their Go packages into C-style shared libraries, Go programmers can easily make their projects work with C, Python, Ruby, Node, Java, etc. using in-process integration of shared object binaries. So, next time you create that killer API in Go, remember to shared with non-Go developers.&lt;/p&gt;

&lt;p&gt;Follow Vladimir on Twitter &lt;a href="https://twitter.com/VladimirVivien" rel="noopener noreferrer"&gt;@vladimirvivien&lt;/a&gt;!&lt;/p&gt;

&lt;p&gt;If you are learning Go, checkout Vladimir Vivien's book on Go, titled &lt;a href="https://www.packtpub.com/application-development/learning-go-programming" rel="noopener noreferrer"&gt;&lt;em&gt;Learning Go Programming&lt;/em&gt;&lt;/a&gt; from Packt Publishing.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.packtpub.com/application-development/learning-go-programming" rel="noopener noreferrer"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fvladimirvivien.github.io%2Flearning-go%2Ffront-cover-small-243x300.jpg" alt="Learning Go Programming Book"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This post was originally published on Medium by its author Vladimir Vivien as &lt;a href="https://medium.com/learning-the-go-programming-language/calling-go-functions-from-other-languages-4c7d8bcc69bf#.bwzvuz988" rel="noopener noreferrer"&gt;&lt;em&gt;Calling Go Functions from other Languages&lt;/em&gt;&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>go</category>
      <category>programming</category>
      <category>goprogramming</category>
      <category>golangprogramming</category>
    </item>
    <item>
      <title>Bit Hacking with Go</title>
      <dc:creator>Vladimir Vivien</dc:creator>
      <pubDate>Fri, 03 Feb 2017 23:21:26 +0000</pubDate>
      <link>https://dev.to/vladimirvivien/bit-hacking-with-go</link>
      <guid>https://dev.to/vladimirvivien/bit-hacking-with-go</guid>
      <description>&lt;p&gt;In the good old days of computing when memory was expensive and processing power was at premium, hacking on bits directly was the preferred (in some cases the only) way to process information. Today, direct bit manipulation is still crucial in many computing use cases such as low-level system programming, image processing, cryptography, etc.&lt;/p&gt;

&lt;p&gt;The Go programming language supports several bitwise operators including the followings:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; &amp;amp;   bitwise AND
 |   bitwise OR
 ^   bitwise XOR
&amp;amp;^   AND NOT
&amp;lt;&amp;lt;   left shift
&amp;gt;&amp;gt;   right shift
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The remainder of this writeup provides a detail discussion of each operator and include examples how they can be used.&lt;/p&gt;

&lt;h1&gt;
  
  
  The &amp;amp; Operator
&lt;/h1&gt;

&lt;p&gt;In Go, the &lt;code&gt;&amp;amp;&lt;/code&gt; operator performs the bitwise &lt;code&gt;AND&lt;/code&gt; operation between two integer operands. Recall that the &lt;code&gt;AND&lt;/code&gt; operation has the following properties:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Given operands a, b
AND(a, b) = 1; only if a = b = 1
               else = 0
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;AND&lt;/code&gt; operator has the nice side effect of selectively clearing bits of an integer value to zero. For instance, we can use the &lt;code&gt;&amp;amp;&lt;/code&gt; operator to clear (set to zero) the last 4 least significant bits (LSB) to all zeros.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func main() {
    var x uint8 = 0xAC    // x = 10101100
    x = x &amp;amp; 0xF0          // x = 10100000
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;All binary operators support the short-hand compound assignment form. For instance, the previous example can be re-written as follows.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func main() {
    var x uint8 = 0xAC    // x = 10101100
    x &amp;amp;= 0xF0             // x = 10100000
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Another neat trick you can do with &lt;code&gt;&amp;amp;&lt;/code&gt; operator is to test whether a number is odd or even. This works because a number is odd when its least significant bit is set (equal 1). We can use the &lt;code&gt;&amp;amp;&lt;/code&gt; operator apply a bitwise &lt;code&gt;AND&lt;/code&gt; operation to an integer the value of 1. If the result is 1, then the original number is odd.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import (
    "fmt"
    "math/rand"
)
func main() {
    for x := 0; x &amp;lt; 100; x++ {
        num := rand.Int()
        if num&amp;amp;1 == 1 {
            fmt.Printf("%d is odd\n", num)
        } else {
            fmt.Printf("%d is even\n", num)
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Run on the &lt;a href="https://play.golang.org/p/2mTNOtioNM" rel="noopener noreferrer"&gt;Playground&lt;/a&gt;.&lt;/p&gt;

&lt;h1&gt;
  
  
  The | Operator
&lt;/h1&gt;

&lt;p&gt;The &lt;code&gt;|&lt;/code&gt; performs a bitwise &lt;code&gt;OR&lt;/code&gt; operation on its integer operands. Recall the &lt;code&gt;OR&lt;/code&gt; operator has the following properties:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Given operands a, b
OR(a, b) = 1; when a = 1 or b = 1
              else = 0 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can use the nature of the bitwise &lt;code&gt;OR&lt;/code&gt; operator to selectively set individual bits for a given integer. For instance, in the following example we use the &lt;code&gt;OR&lt;/code&gt; operator to set (from least to most significant bits (MSB)) the 3rd, 7th, and 8th bit to 1.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func main() {
    var a uint8 = 0
    a |= 196
    fmt.Printf("%b", a)
}

// prints 11000100
          ^^   ^    
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Run on &lt;a href="https://play.golang.org/p/3VPv4D83Oj" rel="noopener noreferrer"&gt;Playground&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Using &lt;code&gt;OR&lt;/code&gt; is quite useful when doing bit masking techniques to set arbitrary bits for a given integer value. For instance, we can expand the previous program to set more bits in the value stored in variable &lt;code&gt;a&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func main() {
    var a uint8 = 0
    a |= 196
    a |= 3
    fmt.Printf("%b", a)
}

// prints 11000111
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Run on &lt;a href="https://play.golang.org/p/7aJLwh3y4x" rel="noopener noreferrer"&gt;Playground&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The previous program, not only has the bits for decimal 196 set, it also has the the last 2 LSBs set for decimal value 3. We can continue on (OR'ing values) until all bit fields in the integer value are set.&lt;/p&gt;

&lt;h3&gt;
  
  
  Bits as Configuration
&lt;/h3&gt;

&lt;p&gt;Now, recall that &lt;code&gt;AND(a, 1) = a if and only if a = 1&lt;/code&gt;. We can use that fact to query a value for its set bits. For instance, from the code above &lt;code&gt;a &amp;amp; 196&lt;/code&gt; will return 196 because the bits for that value are indeed set in &lt;code&gt;a&lt;/code&gt;. So we can combine the use of the &lt;code&gt;OR&lt;/code&gt; and the &lt;code&gt;AND&lt;/code&gt; as a way of specifying configuration values and reading them respectively.&lt;/p&gt;

&lt;p&gt;The following source code snippet shows this at work. Function &lt;code&gt;procstr&lt;/code&gt; transforms the content of a string. It takes two parameters: the first parameter, &lt;code&gt;str&lt;/code&gt;, is the string to be transformed and the second parameter, &lt;code&gt;conf&lt;/code&gt;, is an integer used to specify multiple transformation configurations using bit masking.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const (
    UPPER  = 1 // upper case
    LOWER  = 2 // lower case
    CAP    = 4 // capitalizes
    REV    = 8 // reverses
)

func main() {
    fmt.Println(procstr("HELLO PEOPLE!", LOWER|REV|CAP))
}

func procstr(str string, conf byte) string {
    // reverse string
    rev := func(s string) string {
        runes := []rune(s)
        n := len(runes)
        for i := 0; i &amp;lt; n/2; i++ {
            runes[i], runes[n-1-i] = runes[n-1-i], runes[i]
        }
        return string(runes)
    }

    // query config bits
    if (conf &amp;amp; UPPER) != 0 {
        str = strings.ToUpper(str)
    }
    if (conf &amp;amp; LOWER) != 0 {
        str = strings.ToLower(str)
    }
    if (conf &amp;amp; CAP) != 0 {
        str = strings.Title(str)
    }
    if (conf &amp;amp; REV) != 0 {
        str = rev(str)
    }
    return str
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Run on Go &lt;a href="https://play.golang.org/p/4E05PQwj5q" rel="noopener noreferrer"&gt;Playground&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Function call &lt;code&gt;procstr("HELLO PEOPLE!", LOWER|REV|CAP)&lt;/code&gt; above will lower the cases for the string, reverse its order, and capitalize each word. This is done by setting the 2nd, 3rd, and 4th bits, of parameter &lt;code&gt;conf&lt;/code&gt;, for a value of 14. The code then uses the successive if-statement blocks to extract those bits and apply the proper string transformation.&lt;/p&gt;

&lt;h1&gt;
  
  
  The ^ Operator
&lt;/h1&gt;

&lt;p&gt;The &lt;code&gt;XOR&lt;/code&gt; operator is applied using &lt;code&gt;^&lt;/code&gt; in Go. The &lt;code&gt;XOR&lt;/code&gt;, exclusive OR, has the following properties:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Given operands a, b
XOR(a, b) = 1; only if a != b
     else = 0
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The implication of this definition is that &lt;code&gt;XOR&lt;/code&gt; can be used to toggle bits from one value to another. For instance, given a 16-bit value, we can toggle the first eight bits (starting from the MSB) using the following code.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func main() {
    var a uint16 = 0xCEFF
    a ^= 0xFF00 // same a = a ^ 0xFF00
}

// a = 0xCEFF   (11001110 11111111)
// a ^=0xFF00   (00110001 11111111)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the previous snippet, the bits that are XOR'd with 1 are flipped (going from 0 to 1 or from 1 to 0). One practical use of &lt;code&gt;XOR&lt;/code&gt;, for instance, is to compare sign magnitudes. Two integers a, b have the same signs when &lt;code&gt;(a ^ b) ≥ 0&lt;/code&gt; (or &lt;code&gt;(a ^ b) &amp;lt; 0&lt;/code&gt; for opposite sign) is true as shown in the following program:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func main() {
    a, b := -12, 25
    fmt.Println("a and b have same sign?", (a ^ b) &amp;gt;= 0)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Run on the Go &lt;a href="https://play.golang.org/p/6rAPti5bXJ" rel="noopener noreferrer"&gt;Playground&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;When the previous program is executed, it will print: &lt;code&gt;a and b have same sign? false&lt;/code&gt;. Use the Go Playground link to change the signs of the numbers to see different results.&lt;/p&gt;

&lt;h3&gt;
  
  
  ^ as Bitwise Complement (NOT)
&lt;/h3&gt;

&lt;p&gt;Unlike other languages (c/c++, Java, Python, Javascript, etc), Go does not have a dedicated unary bitwise complement operator. Instead, the &lt;code&gt;XOR&lt;/code&gt; operator, &lt;code&gt;^&lt;/code&gt;, can also be used as a unary operator to apply one's complement to a number. Given bit x, in Go ^x = 1 ^ x which reverses the bit. We can see this in action in the following snippet which uses &lt;code&gt;^a&lt;/code&gt; to take the complement of variable &lt;code&gt;a&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func main() {
    var a byte = 0x0F
    fmt.Printf("%08b\n", a)
    fmt.Printf("%08b\n", ^a)
}

// prints
00001111     // var a
11110000     // ^a
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Run on the &lt;a href="https://play.golang.org/p/5d1fQjDAIv" rel="noopener noreferrer"&gt;Playground&lt;/a&gt;.&lt;/p&gt;

&lt;h1&gt;
  
  
  The &amp;amp;^ Operator
&lt;/h1&gt;

&lt;p&gt;The &lt;code&gt;&amp;amp;^&lt;/code&gt; operator, reads as &lt;code&gt;AND NOT&lt;/code&gt;, is a short-hand form that applies the &lt;code&gt;AND&lt;/code&gt; and the &lt;code&gt;NOT&lt;/code&gt; operations to its operands as shown in the following definition.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Given operands a, b
AND_NOT(a, b) = AND(a, NOT(b))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This has the interesting property of clearing the bits in the first operand if the second operand is 1 as defined here:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;AND_NOT(a, 1) = 0; clears a
AND_NOT(a, 0) = a; 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The next code snippet uses the &lt;code&gt;AND NOT&lt;/code&gt; operator to clear the last four LSBs in variable a from &lt;code&gt;1010 1011&lt;/code&gt; to &lt;code&gt;1010 0000&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func main() {
    var a byte = 0xAB
     fmt.Printf("%08b\n", a)
     a &amp;amp;^= 0x0F
     fmt.Printf("%08b\n", a)
}

// prints:
10101011
10100000
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Run on the &lt;a href="https://play.golang.org/p/UPUlBOPRGh" rel="noopener noreferrer"&gt;Playground&lt;/a&gt;.&lt;/p&gt;

&lt;h1&gt;
  
  
  The &amp;lt;&amp;lt; and &amp;gt;&amp;gt; Operators
&lt;/h1&gt;

&lt;p&gt;Similar to other C-derived languages, Go uses &lt;code&gt;&amp;lt;&amp;lt;&lt;/code&gt; and &lt;code&gt;&amp;gt;&amp;gt;&lt;/code&gt; to represent the left and the right shift operators respectively as defined as below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Given integer operands a and n,
a &amp;lt;&amp;lt; n; shifts all bits in a to the left n times
a &amp;gt;&amp;gt; n; shifts all bits in a to the right n times
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For instance, in the following snippet the left shift operator is used to shift the value stored in &lt;code&gt;a&lt;/code&gt; (&lt;code&gt;00000011&lt;/code&gt;) three times to the left. Each time the result is printed for illustrative purpose.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func main() {
    var a int8 = 3
    fmt.Printf("%08b\n", a)
    fmt.Printf("%08b\n", a&amp;lt;&amp;lt;1)
    fmt.Printf("%08b\n", a&amp;lt;&amp;lt;2)
    fmt.Printf("%08b\n", a&amp;lt;&amp;lt;3)
}

// prints:
00000011
00000110
00001100
00011000
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Run on &lt;a href="https://play.golang.org/p/_lhE8OoZxY" rel="noopener noreferrer"&gt;Playground&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Notice that with each shift, the LSB on the right is zero-filled. Inversely, using the right shift operator each bit in a value can shift to the right with the MSB zero-filled on the left as shown in the following example (signed numbers has an exception, see the &lt;em&gt;Note on Arithmetic Shifts&lt;/em&gt; below).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func main() {
 var a uint8 = 120
 fmt.Printf("%08b\n", a)
 fmt.Printf("%08b\n", a&amp;gt;&amp;gt;1)
 fmt.Printf("%08b\n", a&amp;gt;&amp;gt;2)
}

// prints:
01111000
00111100
00011110
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Run on the &lt;a href="https://play.golang.org/p/mO3SbeltxZ" rel="noopener noreferrer"&gt;Playground&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Some of the simplest tricks that can be done with the left and right shift operators are the multiplication and division where each shift position represents a power of two. For instance, the following divides &lt;code&gt;200&lt;/code&gt; (stored in a) by &lt;code&gt;2&lt;/code&gt; with a right shift.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func main() {
    a := 200
    fmt.Printf("%d\n", a&amp;gt;&amp;gt;1)
}

// prints:
100
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Run on the &lt;a href="https://play.golang.org/p/EJi0YCARun" rel="noopener noreferrer"&gt;Playground&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Or to multiply the value by 4, left shift by 2:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func main() {
    a := 12
    fmt.Printf("%d\n", a&amp;lt;&amp;lt;2)
}
// prints:

48
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Run on the &lt;a href="https://play.golang.org/p/xuJRcKgMVV" rel="noopener noreferrer"&gt;Playground&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The shift operators provides interesting ways to manipulate bits at designated position in a binary value. For instance, in the following snippet, the &lt;code&gt;|&lt;/code&gt; and &lt;code&gt;&amp;lt;&amp;lt;&lt;/code&gt; operators are used to set the 3rd bit in variable &lt;code&gt;a&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func main() {
    var a int8 = 8
    fmt.Printf("%08b\n", a)
    a = a | (1&amp;lt;&amp;lt;2)
    fmt.Printf("%08b\n", a)
}
// prints:
00001000
00001100
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Run on the &lt;a href="https://play.golang.org/p/h7WoP7ieuI" rel="noopener noreferrer"&gt;Playground&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Or you can combine the shift and the &lt;code&gt;&amp;amp;&lt;/code&gt; operators to test if nth bit is set in a value as demonstrated in the following snippet.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func main() {
    var a int8 = 12
    if a&amp;amp;(1&amp;lt;&amp;lt;2) != 0 {
        fmt.Println("take action")
    }
}

// prints:
take action
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Run on the &lt;a href="https://play.golang.org/p/Ptc7Txk5Jb" rel="noopener noreferrer"&gt;Playground&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Using the &lt;code&gt;&amp;amp;^&lt;/code&gt; and the shift operators, we can unset the nth bit of a value. For instance, the following snippet unsets the third bit in variable a.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func main() {
    var a int8 = 13 
    fmt.Printf("%04b\n", a)
    a = a &amp;amp;^ (1 &amp;lt;&amp;lt; 2)
    fmt.Printf("%04b\n", a)
}

// prints:
1101
1001
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Run on the &lt;a href="https://play.golang.org/p/Stjq9oOjKz" rel="noopener noreferrer"&gt;Playground&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  A Note on Arithmetic Shifts
&lt;/h3&gt;

&lt;p&gt;When the value to be shifted (the left operand) is a signed value, Go automatically apply arithmetic shifts. During a right shift operation, the (two's complement) sign bit is copied (or extended) to fill the shifted slots.&lt;/p&gt;

&lt;h1&gt;
  
  
  Conclusion
&lt;/h1&gt;

&lt;p&gt;As with other modern languages, Go supports all bitwise operators. This writeup only provided an small sample of the sorts of bit hacks that can be done with these operators. You can find a lot more recipes online, specifically from &lt;a href="https://graphics.stanford.edu/~seander/bithacks.html" rel="noopener noreferrer"&gt;Bit Twiddling Hacks&lt;/a&gt; by Sean Eron Anderson.&lt;/p&gt;

&lt;p&gt;Follow Vladimir on Twitter &lt;a href="https://twitter.com/VladimirVivien" rel="noopener noreferrer"&gt;@vladimirvivien&lt;/a&gt;!&lt;/p&gt;

&lt;p&gt;If you are learning Go, checkout Vladimir Vivien's book on Go, titled &lt;a href="https://www.packtpub.com/application-development/learning-go-programming" rel="noopener noreferrer"&gt;&lt;em&gt;Learning Go Programming&lt;/em&gt;&lt;/a&gt; from Packt Publishing.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.packtpub.com/application-development/learning-go-programming" rel="noopener noreferrer"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fvladimirvivien.github.io%2Flearning-go%2Ffront-cover-small-243x300.jpg" alt="Learning Go Programming Book"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This post was originally published on Medium by its author Vladimir Vivien as &lt;a href="https://medium.com/learning-the-go-programming-language/bit-hacking-with-go-e0acee258827#.2hof13ia5" rel="noopener noreferrer"&gt;&lt;em&gt;Bit Hacking with Go&lt;/em&gt;&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>go</category>
      <category>programming</category>
      <category>goprogramming</category>
    </item>
    <item>
      <title>Vladimir Vivien</title>
      <dc:creator>Vladimir Vivien</dc:creator>
      <pubDate>Fri, 03 Feb 2017 19:07:45 +0000</pubDate>
      <link>https://dev.to/vladimirvivien/vladimir-vivien</link>
      <guid>https://dev.to/vladimirvivien/vladimir-vivien</guid>
      <description>&lt;p&gt;Hi, I am Vladimir Vivien, a software engineer in the US.  I have been coding since floppy disks were a thing.  &lt;/p&gt;

&lt;p&gt;Currently, I primarily work on Go open source projects for fun (&lt;a href="https://github.com/vladimirvivien" rel="noopener noreferrer"&gt;github.com/vladimirvivien&lt;/a&gt;) and profit (at {code} by Dell EMC).&lt;/p&gt;

&lt;p&gt;I enjoyed Go so much that I published an introductory book in Go titled &lt;a href="https://www.packtpub.com/application-development/learning-go-programming" rel="noopener noreferrer"&gt;Learning Go Programming&lt;/a&gt; from Packt.  &lt;/p&gt;

&lt;p&gt;When I am not slinging code, I enjoy spending time with my family, playing with my beat-making gears and reading about (and playing with) technology.&lt;/p&gt;

</description>
      <category>introduction</category>
    </item>
  </channel>
</rss>
