Skip to content

Instantly share code, notes, and snippets.

@50n1cd347h9
Last active February 20, 2025 07:55
Show Gist options
  • Save 50n1cd347h9/d1ea4c179009e2d4cd4b976ae2e0c78f to your computer and use it in GitHub Desktop.
Save 50n1cd347h9/d1ea4c179009e2d4cd4b976ae2e0c78f to your computer and use it in GitHub Desktop.
const std = @import("std");
const stdin = std.io.getStdIn().reader();
const stdout = std.io.getStdOut().writer();
const ParseError = error{Fail};
var index: usize = 0;
fn nextChar(buf: []const u8) u8 {
defer index += 1;
return buf[index];
}
fn isDigit(ch: u8) bool {
const code = @as(i8, @intCast(ch));
return code - '0' < 10 and code - '0' >= 0;
}
fn parseFloatingPoint(buf: []const u8) !f32 {
var b: i32 = 0;
var e: i32 = 0;
var i: i32 = 0;
var sign: u8 = '+';
var ch = nextChar(buf);
blk: {
if (ch == '.') {
ch = nextChar(buf);
if (isDigit(ch)) {}
b = ch - '0';
e = 1;
} else if (isDigit(ch)) {
b = 10 * b + ch - '0';
ch = nextChar(buf);
while (isDigit(ch)) {
b = 10 * b + ch - '0';
ch = nextChar(buf);
}
if (ch == 'E') break :blk;
if (ch != '.') return ParseError.Fail;
} else {
return ParseError.Fail;
}
ch = nextChar(buf);
while (isDigit(ch)) {
b = 10 * b + ch - '0';
e += 1;
ch = nextChar(buf);
}
if (ch != 'E') break :blk;
}
blk: {
ch = nextChar(buf);
if (ch == '+' or ch == '-') {
sign = ch;
ch = nextChar(buf);
} else break :blk;
while (isDigit(ch)) {
i = 10 * i + ch - '0';
ch = nextChar(buf);
}
}
const sign_num: i32 = if (sign == '+') 1 else -1;
return @as(f32, @floatFromInt(b)) * std.math.pow(f32, 10, @floatFromInt(sign_num * i - e));
}
pub fn main() !void {
var buf = [_]u8{0} ** 0x100;
try stdout.print("input floating point number >> ", .{});
_ = try stdin.readUntilDelimiter(&buf, '\n');
try stdout.print("accepted: {}\n", .{try parseFloatingPoint(&buf)});
}
test "digit" {
const digits = [_]u8{ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
for (digits) |digit|
try std.testing.expect(isDigit(digit));
try std.testing.expect(!isDigit(':'));
try std.testing.expect(!isDigit('/'));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment