Android Question Need bytes of a hex string

techknight

Well-Known Member
Licensed User
Longtime User
Lets say I have a string like this:

"003C428181A5A581A5BD9981423C0000"

I need a byte array of that string.

The simplest thing I tried was String.GetBytes("UTF8")

But that didnt work, it gave me the ASCII values of each in an array, and thats not what I want. I want 00 Hex = 0 in the byte array, and 3C is 60 in the byte array.

How do I do this? thanks.
 

eurojam

Well-Known Member
Licensed User
Longtime User
did you try the byteconverter Lib:
B4X:
Dim bconv As ByteConverter
Dim data() As Byte
data = bconv.HexToBytes("003C428181A5A581A5BD9981423C0000")
 
Upvote 0

sorex

Expert
Licensed User
Longtime User
you mean this?

B4X:
Dim hex As String="003C428181A5A581A5BD9981423C0000"
Dim values As Map
values.Initialize
For x=0 To hex.Length-1 Step 2
values.Put(x/2,Bit.ParseInt ( hex.CharAt(x) & hex.CharAt(x+1) ,16 ))
Next

For x=0 To values.Size-1
Log(values.GetValueAt(x))  
Next

which outputs

** Activity (main) Create, isFirst = true **
0
60
66
129
129
165
165
129
165
189
153
129
66
60
0
0
** Activity (main) Resume **
 
Upvote 0

techknight

Well-Known Member
Licensed User
Longtime User
Thats what I needed. I remember doing this before, but my memory escapes me...

Hey, another question: Is it possible to read and set specific bits in a byte? I have a subroutine that sets a bit, but I dont know exactly how to read a bit. The bit location number needs to be in a variable. So setting and reading bits in a loop...
 
Upvote 0

JordiCP

Expert
Licensed User
Longtime User
To read bits
B4X:
Dim a as Byte= 0xAA
if Bit.And(a,0x80)<>0 then
  ....
end if
or also
B4X:
Dim num_bit as Int=7 ' 0 will correspond to mask 0x01 and 7 to mask 0x80
if Bit.AND(a,Bit.ShiftLeft(1,num_bit)) then
...
end if

To set bits
B4X:
a=Bit.OR(a,0x40)  'will return a=0xEA
or also
B4X:
Dim num_bit as int=6
a=Bit.OR(a,Bit.ShifLeft(1,num_bit))
 
Upvote 0

techknight

Well-Known Member
Licensed User
Longtime User
New problem:

If I add this to a string: Chr(176) (degrees symbol)

The getbytes gives me a -62 for that, which of course is a negative number and crashing my loop.

any ideas how to fix that?
 
Upvote 0
Top