brainfuck Powershell interpreter
Jump to navigation
Jump to search
The following is a Powershell implementation of brainfuck by User:None1, the first line in the input is the program, and the rest are the input. EOF returns 0.
$code=Read-Host
function getchar(){
return [System.Console]::Read()
}
function putchar($x){ # Output a character
[System.Console]::Write([Convert]::ToChar($x))
}
$ip=0
$tape=[int[]]::new(1000000)
$p=0
while($ip -lt $code.Length){
$c=$code[$ip]
if($c -eq "+"){
$tape[$p]=($tape[$p]+1)%256
}
if($c -eq "-"){
$tape[$p]=($tape[$p]+255)%256
}
if($c -eq ","){
$tape[$p]=getchar
if($tape[$p] -eq -1){ # Deal with EOF
$tape[$p]=0
}
if($tape[$p] -eq 13){ # Deal with Windows's CRLF
$tape[$p]=getchar
}
}
if($c -eq "."){
putchar($tape[$p])
}
if($c -eq '>'){
$p++;
}
if($c -eq '<'){
$p--;
}
if($c -eq '['){
if($tape[$p] -eq 0){
$loop=1
while($loop -gt 0){
$ip++
if($code[$ip] -eq '['){
$loop++
}
if($code[$ip] -eq ']'){
$loop--
}
}
}
}
if($c -eq ']'){
$loop=1
while($loop -gt 0){
$ip--
if($code[$ip] -eq '['){
$loop--
}
if($code[$ip] -eq ']'){
$loop++
}
}
$ip--
}
$ip++
}