当前位置:首页 > 编程笔记 > 正文
已解决

brainfuck解析器

来自网友在路上 180880提问 提问时间:2023-09-19 04:09:41阅读次数: 80

最佳答案 问答题库808位专家为你答疑解惑

看到一个有趣的问题

用不超过512个字符的brainfuck语言代码,输出一个尽可能大的数?2 关注 · 2 回答问题

看了下brainfuck的语法,极其简单。

尝试写了一个解释器,顺便测试了下,挺有趣的。

package mainimport ("os""reflect""strconv""unsafe"
)func BytesToString(data []byte) string {return *(*string)(unsafe.Pointer(&data))
}
func StringToReadBytes(data string) []byte {stringHeader := (*reflect.StringHeader)(unsafe.Pointer(&data))byteHeader := reflect.SliceHeader{Data: stringHeader.Data,Len:  stringHeader.Len,Cap:  stringHeader.Len,}return *(*[]byte)(unsafe.Pointer(&byteHeader))
}type Stack struct {Data  []intCount int
}func (this *Stack) Push(n int) {if len(this.Data) <= this.Count {this.Data = append(this.Data, 0)}this.Data[this.Count] = nthis.Count++
}func (this *Stack) Pop() int {if this.Count == 0 {return 0}this.Count--return this.Data[this.Count]
}func main() {args := os.ArgsdataMaxLen := 10240code := "-[>-[>+++++++[>++++++++<-]>.[-]<<-]<-]" //测试codecodeIndex := 0outMaxLen := 1024input := []uint8{}inputIndex := 0argsNum := len(args)if argsNum >= 2 {code = args[1]}if argsNum >= 3 {input = StringToReadBytes(args[2])}if argsNum >= 4 {tmpNum, err := strconv.ParseUint(args[3], 10, 64)if err == nil {dataMaxLen = int(tmpNum)}}if argsNum >= 5 {tmpNum, err := strconv.ParseUint(args[4], 10, 64)if err == nil {outMaxLen = int(tmpNum)}}data := make([]uint8, dataMaxLen)dataIndex := dataMaxLen / 2stack := &Stack{}out := make([]uint8, outMaxLen)outIndex := 0println("code:", code, ";input:", BytesToString(input))for codeIndex < len(code) {switch code[codeIndex] {case '>':dataIndex++if dataIndex >= dataMaxLen {print("data index:", dataIndex, " out")return}codeIndex++breakcase '<':dataIndex--if dataIndex < 0 {print("data index:", dataIndex, " out")return}codeIndex++breakcase '+':data[dataIndex]++codeIndex++breakcase '-':data[dataIndex]--codeIndex++breakcase '.':if outIndex < outMaxLen {out[outIndex] = data[dataIndex]outIndex++}codeIndex++breakcase ',':if inputIndex < len(input) {data[dataIndex] = input[inputIndex]inputIndex++} else {data[dataIndex] = 0}codeIndex++breakcase '[':if data[dataIndex] != 0 { //进入循环体stack.Push(codeIndex)codeIndex++} else { //跳出left := 0for codeIndex < len(code) {if code[codeIndex] == '[' {left++} else if code[codeIndex] == ']' {left--if left == 0 {codeIndex++break}}codeIndex++}}breakcase ']':if stack.Count == 0 {codeIndex++break}codeIndex = stack.Pop()breakdefault:codeIndex++break}}//把输出内容一次性输出print(BytesToString(out[:outIndex]))
}
查看全文

99%的人还看了

相似问题

猜你感兴趣

版权申明

本文"brainfuck解析器":http://eshow365.cn/6-9098-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!