go for binary integer conversion

go has been achieved int-> bin conversion function, I am here just to realize the logic of the process, as the principle I assume we all know

This case only consider int-> bin conversion

It contains a positive integer, negative integer, the conversion 0

 

main Package 

Import ( 
    " FMT " 
    " StrConv " 
) 

// bin represents the number of bits after conversion 
FUNC convertToBin (n- int , bin int ) String {
     var B String 
    Switch {
     Case n-== 0 :
         for I: = 0 ; I < bin; I ++ { 
            B + = " 0 " 
        } 
    Case n-> 0 :
         // strcov.Itoa into the 1 "1", string (1) directly into assic code 
        for ; n->0 ; n-/ = 2 { 
            B = strconv.Itoa (% n- 2 ) + B 
        } 
        // Add 0 
        J: bin- = len (B)
         for   I: = 0 ; I <J; I ++ { 
            B = " 0 " + B 
        } 
    Case n-< 0 : 
        n- = n-* - . 1 
        // fmt.Println ( "becomes an integer:", n-) 
        S: = convertToBin (n-, bin)
         // fmt.Println ( "bin:", S )
         // negated 
        for I: = 0; I <len (S); I ++ {
             IF S [I: I + . 1 ] == " . 1 " { 
                B + = " 0 " 
            } the else { 
                B + = " . 1 " 
            } 
        } 
        // fmt.Println ( "bin ~ : ", B)
         // converted to shaping, after the addition of 1 to 64 here have, in the conversion process may otherwise be out of range 
        n-, ERR: = strconv.ParseInt (B, 2 , 64 )
         IF ! ERR = nil { 
            FMT .Println (ERR) 
        } 
        // into bin
        //+1
        b=convertToBin(int(n+1),bin)
    }
    return b
}

func main(){
    fmt.Println(
        convertToBin(5,8),  //101
        convertToBin(13,8), //1101
        convertToBin(11111,8),
        convertToBin(0,8),
        convertToBin(1,8),
        convertToBin(-5, 8 ), 
        convertToBin ( - 11111 , 8 ) 
    ) 
}

result:

5     13      11111      0    1      -5    -11111
00000101
00001101 10101101100111 00000000 00000001 11111011 1010010011001

 

For example, -11,111 transformation:

Becomes an integer: 11111 
bin: 10,101,101,100,111 
~ bin: 01010010011000 
Results: 1010010011001

 

-1 such conversions:

Becomes an integer: . 1 
bin: 00000001 
~ bin: 11111110
Results: 11111111

 

Guess you like

Origin www.cnblogs.com/feiquan/p/11256377.html