package main

import (
	"fmt"
)
type parser struct {
	err error // Last error seen
}

func parseNumeric(b []byte) int64 {
	// Check for base-256 (binary) format first.
	// If the first bit is set, then all following bits constitute a two's
	// complement encoded number in big-endian byte order.

	if len(b) > 0 && b[0]&0x80 != 0 {
		// Handling negative numbers relies on the following identity:
		//	-a-1 == ^a
		//
		// If the number is negative, we use an inversion mask to invert the
		// data bytes and treat the value as an unsigned number.
		var inv byte // 0x00 if positive or zero, 0xff if negative
		if b[0]&0x40 != 0 {
			inv = 0xff
		}

		var x uint64
		for i, c := range b {
			c ^= inv // Inverts c only if inv is 0xff, otherwise does nothing
			if i == 0 {
				c &= 0x7f // Ignore signal bit in first byte
			}
                        fmt.Println(x)
			if (x >> 56) > 0 {
				//p.err = 'what' // Integer overflow
				return 0
			}
			x = x<<8 | uint64(c)
		}

                if (x >> 63) > 0 {
                  //p.err = 'whtat' // Integer overflow
			return 0
		}
		if inv == 0xff {
			return ^int64(x)
		}
		return int64(x)
	}
        return int64(0)
	// Normal case is base-8 (octal) format.
	//return p.parseOctal(b)
}

func fitsInBase256(n int, x int64) bool {
	var binBits = uint(n-1) * 8
/*         fmt.Println("x=") */
        /* fmt.Println(x) */

	return n >= 9 || (x >= -1<<binBits && x < 1<<binBits)
}

func formatNumeric(b []byte, x int64) {
  fmt.Println(x)
	if fitsInBase256(len(b), x) {
		for i := len(b) - 1; i >= 0; i-- {
                        // fmt.Println(x)
                        // fmt.Println("%v",byte(x))
                        fmt.Println(byte(x))
			b[i] = byte(x)
			x >>= 8
		}
		b[0] |= 0x80 // Highest bit indicates binary format
		return
	}

	// f.formatOctal(b, 0) // Last resort, just write zero
	// f.err = ErrFieldTooLong
}

func main() {
//"\x87\x76\xa2\x22\xeb\x8a\x72\x61"
//if len(b) > 0 && b[0]&0x80 != 0 {
        // var b = make([]byte, len("\x80\x00\x00\x31\xff\xff\xff\xff\xff\xff"))
        /* fmt.Println(string(b) == "\xff\xff\xff\xff\xf7\x76\xa2\x22\xeb\x8a\x72\x61") */
/*         fmt.Println(len("\xff\xff\xff\xff\xf7\x76\xa2\x22\xeb\x8a\x72\x61")) */

        // formatNumeric(b, -9007199254740735)

        // fmt.Println("%v", b)


        //%v [255 255 255 224 0 0 0 0 1 1]
        //%v [128 0 0 31 255 255 255 255 254 255]
         // [128 0 0 31 255 255 255 255 255 255]
        // fmt.Println((-1<<0))
        // fmt.Println((1<<0))

        // fmt.Println(string(b))
/*         var b = make([]byte, len("\x80\x00\x00\x1f\xff\xff\xff\xff\xfe\xff")) */
        // parseNumeric(b)
        /* fmt.Println(string(b)) */
        /* fmt.Println(string(b) == "\xff\xff\xff\xff\xf7\x76\xa2\x22\xeb\x8a\x72\x61") */
        // fmt.Println(parseNumeric([] byte("\x80\x00\x00\x1f\xff\xff\xff\xff\xfe\xff")))
        fmt.Println(536870911<<8)
	//fmt.Println("\x87\x76\xa2\x22\xeb\x8a\x72\x61"[0]&0x80)
}

