Solution Making TeX Treat Characters like Words
This works, but has the limitation that denoted characters do not work. e.g. using hexidecimal (\char"02C6) or octal notation.
\documentclass{article}
\def\hash#1{\xscan#1\relax}% calls xscan which looks ahead one token, #1
\def\xscan{\afterassignment\xxscan\let\token= }% assign single token to \token and call \xxscan
\def\xxscan{%
\ttfamily% set font style
\ifx\token\relax\ttfamily\else%test for end-of-line or end of group and switch to ttfamily
\ifcat\token\space%
\token% token is catcode 10
\spaceskip=.5em% remove glue from space for fixed-width space
\xspaceskip=.5em% remove glue from space for fixed-width space
\else%
\token\hskip 0pt plus 1sp minus 1sp % add glue to any non-catcode 10 (space)
\fi
\spaceskip=0pt% reset space skip
\expandafter\xscan% feed next token to \xscan, which is effectively a recursive call
\fi}
\begin{document}
SHA-256 is a hash function with a 256-bit long output: \hash{d270f747a8743f11aef93c10e9cb6932cc0b862464c1133dc0f8889088740d15}
%SHA-256 is a hash function with a 256-bit long output: \hash{d270f\char"02C6\relax747a8743f11aef93c10e9cb6932cc0b862464c1133dc0f8889088740d15}% \char" denoted char syntax not supported
\end{document}
Related: How can I make LaTeX to recognize spaces in my macro (catcode 10)?
Solution Using Intercharacter Tokens
\XeTeXinterchartokenstate=1 % turn them on
\XeTeXinterchartoks 0 0 = {\penalty0\relax}#1} % use insert token
This is my preferred solution if using TeX Live 2017 and using xelatex. This has the advantage that it supports the original capabilities of \texttt-it should-like denoted characters (see comments under David Carlisle's answer).
\documentclass{article}
\newcommand{\hash}[1]{\texttt{\XeTeXinterchartokenstate=1\XeTeXinterchartoks 0 0 = {\penalty0\relax}#1}}%In a perfect world, this would be changed to allow linebreaks anywhere in #1
\begin{document}
SHA-256 is a hash function with a 256-bit long output: \hash{d270f747a8743f11aef93c10e9cb6932cc0b862464c1133dc0f8889088740d15}
SHA-256 is a hash function with a 256-bit long output: \hash{d270f\char"02C6\relax747a8743f11aef93c10e9cb6932cc0b862464c1133dc0f8889088740d15}
\end{document}
\hash{this\ a\ word}, whitespace will be keeped. – Tokubara Apr 08 '23 at 09:39