How to convert from 4-bit hexadecimal to 7-bit ASCII?

百般思念 提交于 2019-12-03 16:29:26

When you mask off the lower four bits, you have the potential for ending up with the values 0x0 to 0xF. The table of desired results is:

0x0 -> '0' = 0x30
0x1 -> '1' = 0x31
0x2 -> '2' = 0x32
0x3 -> '3' = 0x33
0x4 -> '4' = 0x34
0x5 -> '5' = 0x35
0x6 -> '6' = 0x36
0x7 -> '7' = 0x37
0x8 -> '8' = 0x38
0x9 -> '9' = 0x39
0xA -> 'A' = 0x41
0xB -> 'B' = 0x42
0xC -> 'C' = 0x43
0xD -> 'D' = 0x44
0xE -> 'E' = 0x45
0xF -> 'F' = 0x46

From that table of desired results we can see that there are two linear sections, from 0x0 to 0x9 and from 0xA to 0xF. For the 0x0 to 0x9 case 0x30 - 0x0 = 0x30 so we add 0x30. For the 0xA to 0xF section 0x41 - 0xA = 0x37.

Will that work?

0x0 + 0x30 = 0x30
0x1 + 0x30 = 0x31
0x2 + 0x30 = 0x32
0x3 + 0x30 = 0x33
0x4 + 0x30 = 0x34
0x5 + 0x30 = 0x35
0x6 + 0x30 = 0x36
0x7 + 0x30 = 0x37
0x8 + 0x30 = 0x38
0x9 + 0x30 = 0x39

0xA + 0x37 = 0x41
0xB + 0x37 = 0x42
0xC + 0x37 = 0x43
0xD + 0x37 = 0x44
0xE + 0x37 = 0x45
0xF + 0x37 = 0x46

Looks good.

A slightly different way is always add 0x30 then adjust after.

0x0 + 0x30 = 0x30
0x1 + 0x30 = 0x31
0x2 + 0x30 = 0x32
0x3 + 0x30 = 0x33
0x4 + 0x30 = 0x34
0x5 + 0x30 = 0x35
0x6 + 0x30 = 0x36
0x7 + 0x30 = 0x37
0x8 + 0x30 = 0x38
0x9 + 0x30 = 0x39
0xA + 0x30 + 7 = 0x41
0xB + 0x30 + 7 = 0x42
0xC + 0x30 + 7 = 0x43
0xD + 0x30 + 7 = 0x44
0xE + 0x30 + 7 = 0x45
0xF + 0x30 + 7 = 0x46

When creating the desired result table, the left side you should have known something anded with 0xF gives you 0x0 to 0xF, and it appears you did. The right side of the desired table comes from an ASCII chart. I think if you had made that chart and gotten out a calculator (yea that little thing with buttons that old people use, although one that does hex, your phone should have an app for it). From there visually from that table come up with the algorithm.

You should also ask yourself, what if I want A to F to be lower case instead of upper case (a,b,c,d,e,f)? How do I change the algorithm?

Some errors in the flowchart

1.Mask and keep only last four bytes --> bits
2.Decision 0<x<9 --> 0<=x<=9
3.Decision 9<x<15 --> 9<x<=15 (also superfluous!)

The program

.global hexasc 

    .text
    .align 2

hexasc: movi r8, 0x09
        andi r4, r4, 0x0f #keep only 4 bits
        movi r2, 0x37
        bgt r4, r8, L1  #is x>9?
        movi r2, 0x30
L1:     add r2, r2, r4  
        ret  
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!